macos 为什么这个正则表达式不起作用: find ./ -regex '.*\(m\|h\)$

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5905493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 08:02:29  来源:igfitidea点击:

why isn't this regex working : find ./ -regex '.*\(m\|h\)$

regexmacos

提问by Greg

Why isn't this regex working?

为什么这个正则表达式不起作用?

  find ./ -regex '.*\(m\|h\)$

I noticed that the following works fine:

我注意到以下工作正常:

  find ./ -regex '.*\(m\)$'

But when I add the "or a h at the end of the filename" by adding \|hit doesn't work. That is, it should pick up all my *.mand *.hfiles, but I am getting nothing back.

但是当我在文件名末尾添加“或啊”时,\|h它不起作用。也就是说,它应该拿起我所有的*.m*.h文件,但我得到任何回报。

I am on Mac OS X.

我在 Mac OS X 上。

回答by Mikel

On Mac OS X, you can't use \|in a basic regular expression, which is what finduses by default.

在 Mac OS X 上,您不能\|在基本正则表达式中使用,这是find默认使用的。

re_format man page

re_format 手册页

[basic] regular expressions differ in several respects. | is an ordinary character and there is no equivalent for its functionality.

[基本] 正则表达式在几个方面有所不同。| 是一个普通字符,它的功能没有等价物。

The easiest fix in this case is to change \(m\|h\)to [mh], e.g.

在这种情况下最简单的解决方法是更改\(m\|h\)[mh],例如

find ./ -regex '.*[mh]$'

Or you could add the -Eoption to tell find to use extended regular expressions instead.

或者您可以添加-E选项来告诉 find 使用扩展的正则表达式。

find -E ./ -regex '.*(m|h)$'

Unfortunately -Eisn't portable.

不幸的-E是不便携。

Also note that if you only want to list files ending in .mor .h, you have to escape the dot, e.g.

另请注意,如果您只想列出以.mor结尾的文件.h,则必须对点进行转义,例如

find ./ -regex '.*\.[mh]$'

If you find this confusing (me too), there's a great reference table that shows which features are supported on which systems.

如果您觉得这令人困惑(我也是),这里有一个很好的参考表,其中显示了哪些系统支持哪些功能。

Regex Syntax Summary[Google Cache]

正则表达式语法摘要[ Google 缓存]

回答by Wes

A more efficient solution is to use the -oflag:

更有效的解决方案是使用-o标志:

find . -type f \( -name "*.m" -o -name "*.h" \)

but if you want the regex use:

但如果你想要正则表达式使用:

find . -type f -regex ".*\.[mh]$"

回答by IDBUYTHATFORADOLLAR

Okay this is a little hacky but if you don't want to wrangle the regex limitations of find on OSX, you can just pipe find's output to grep:

好的,这有点 hacky 但如果您不想在 OSX 上纠结 find 的正则表达式限制,您可以将 find 的输出通过管道传递给 grep:

find . | grep ".*\(\h\|m\)"

回答by tchrist

What's wrong with

怎么了

find . -name '*.[mh]' -type f

If you want fancy patterns, then use find2perland hack the pattern.

如果你想要花哨的模式,那么使用find2perl并破解模式。