bash 扩展正则表达式运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12614267/
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-09-18 03:23:19  来源:igfitidea点击:

bash extended regex operators

regexbash

提问by KevinRGT

I am trying to use the extended regex operators available in bash (?, *, +, @, !). The manual says I just have to enclose with parentheses a list of patterns, then use the operator before the left bracket. So if I want a pattern of zero or more a's:

我正在尝试使用 bash 中可用的扩展正则表达式运算符(?、*、+、@、!)。手册说我只需要用括号括起一个模式列表,然后在左括号之前使用运算符。因此,如果我想要零个或多个 a 的模式:

if [[ "" =~ *(a) ]]
then
   echo 
fi

but this is not working. What am I doing wrong?

但这不起作用。我究竟做错了什么?

回答by nneonneo

Per man bash:

man bash:

An additional binary operator, =~, is available, with the same precedence as ==and !=. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex(3)). The return value is 0 if the string matches the pattern, and 1 otherwise. If the regular expression is syntactically incorrect, the conditional expression's return value is 2. If the shell option nocasematchis enabled, the match is performed without regard to the case of alphabetic characters. Any part of the pattern may be quoted to force it to be matched as a string. Substrings matched by parenthesized subexpressions within the regular expression are saved in the array variable BASH_REMATCH. The element of BASH_REMATCHwith index 0 is the portion of the string matching the entire regular expression. The element of BASH_REMATCHwith index nis the portion of the string matching the nth parenthesized subexpression.

额外的二元运算符 ,=~可用,其优先级与==和相同 !=。使用时,运算符右侧的字符串被视为扩展正则表达式并进行相应匹配(如 regex(3))。如果字符串与模式匹配,则返回值为 0,否则为 1。如果正则表达式在语法上不正确,则条件表达式的返回值为 2。如果nocasematch启用了 shell 选项 ,则执行匹配时不考虑字母字符的大小写。可以引用模式的任何部分以强制将其作为字符串进行匹配。正则表达式中括号内子表达式匹配的子串保存在数组变量中BASH_REMATCH. BASH_REMATCH索引为 0的元素是与整个正则表达式匹配的字符串部分。BASH_REMATCH索引为 n的元素是字符串中与第n个带括号的子表达式匹配的部分。

I quoted the whole thing here because I think it's useful to know. You use standard POSIX extended regular expressions on the right hand side.

我在这里引用了整件事,因为我认为了解它很有用。您在右侧使用标准 POSIX 扩展正则表达式。

In particular, the expression on the right side may match a substring of the left operand. Thus, to match the whole string, use ^and $anchors:

特别是,右侧的表达式可能匹配左侧操作数的子字符串。因此,要匹配整个字符串,请使用^$锚点:

if [[ "" =~ ^a*$ ]]
then
    echo 
fi