bash 语法错误 expr
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25587446/
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
Syntax error expr
提问by rudolph9
Why does the following returning a syntax error:
为什么以下返回语法错误:
stringZ=abcABC123ABCabc
echo `expr match "$stringZ" 'abc[A-Z]*.2'`
This works on my ubuntu machine but when I try it on my mac running OS X 10.9.4 I get expr: syntax error
?
这适用于我的 ubuntu 机器,但是当我在运行 OS X 10.9.4 的 mac 上尝试时,我得到了expr: syntax error
?
回答by Wm Annis
This seems like a bash version difference. The :
syntax works on my OSX 10.9.4 machine (which has bash 3.2.51, not very current):
这似乎是 bash 版本的差异。在:
我的OSX 10.9.4机器上的语法著作(其中有庆典51年2月3日,不太电流):
echo `expr "$stringZ" : 'abc[A-Z]*.2'`
回答by Tom Fenech
expr
is quite old-fashioned. On newer bash you may prefer to use the more modern regular expression syntax:
expr
是相当老式的。在较新的 bash 上,您可能更喜欢使用更现代的正则表达式语法:
re='abc[A-Z]*.2'
[[ $stringZ =~ $re ]] && echo ${#BASH_REMATCH}
The =~
operator is available since bash version 3.0. For maximum compatibility across older versions of bash, it is recommendedto store the pattern to be matched in a separate variable and expand it without quotes. Successful matches are stored in the BASH_REMATCH
array. If capturing groups are used, each group will be stored as a separate element in the array.
该=~
运算符从 bash 3.0 版开始可用。为了在旧版本的 bash 中获得最大的兼容性,建议将要匹配的模式存储在一个单独的变量中,并在不带引号的情况下扩展它。成功的匹配存储在BASH_REMATCH
数组中。如果使用捕获组,则每个组将作为单独的元素存储在数组中。