使用负前瞻错误返回 2 的 Bash 双括号正则表达式比较 [英] Bash double bracket regex comparison using negative lookahead error return 2
问题描述
在 Bash 4.1 机器上,
On Bash 4.1 machine,
我正在尝试使用双括号"[[表达式]]
使用NEGATIVE LOOKAHEAD"进行正则表达式比较.
I'm trying to use "double bracket" [[ expression ]]
to do REGEX comparison using "NEGATIVE LOOKAHEAD".
我做了 "set +H
" 来禁用 BASH 变量'!
' 扩展到命令历史搜索.
I did "set +H
" to disable BASH variable'!
' expansion to command history search.
我想匹配任何字符串",除了arm-trusted-firmware".
set +H
if [[ alsa =~ ^(?!arm-trusted-firmware).* ]]; then echo MATCH; else echo "NOT MATCH"; fi
我希望这会打印出MATCH",但它打印不匹配".
I expect this to print "MATCH" back, but it prints "NOT MATCH".
查看双括号"的返回码后,它返回2":
After looking into the return code of "double bracket", it returns "2":
set +H
[[ alsa =~ ^(?!arm-trusted-firmware).* ]]
echo $?
根据bash手册,返回值 '2' 表示正则表达式在语法上不正确":
According to bash manual, the return value '2' means "the regular expression is syntactically incorrect":
一个额外的二元运算符,=~,可用,具有与 == 和 != 相同的优先级.
使用时,运算符右侧的字符串被视为扩展的正则表达式并相应地匹配(如 regex(3)).
如果字符串与模式匹配,则返回值为 0,否则为 1.如果正则表达式在语法上不正确,条件表达式的返回值为 2.
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.
我做错了什么?
在我的原始脚本中,我正在与 STRING 列表进行比较.
In my original script, I'm comparing against to a list of STRINGs.
当它匹配时,我触发一些函数调用;
When it matches, I trigger some function calls;
当它不匹配时,我会跳过我的操作.
when it doesn't match, I skip my actions.
所以,是的,从这个例子来看,
So, YES, from this example,
我正在比较alsa"和arm-trusted-firmware"之间的字符串.
I'm comparing literally the STRING between 'alsa' and 'arm-trusted-firmware'.
推荐答案
默认情况下 bash POSIX 标准不支持 PCRE.(来源:Wiki Bash 黑客)
By default bash POSIX standard doesn't supports PCRE. (source: Wiki Bash Hackers)
作为解决方法,您需要启用 extglob
.这将启用一些扩展的全局模式:
As workaround, you'll need to enable extglob
. This will enable some extended globing patterns:
$ shopt -s extglob
查看 Wooledge Wiki 以了解有关 extglob
的更多信息.
Check Wooledge Wiki for reading more about extglob
.
然后你就可以使用这样的模式了:
Then you'll be able to use patterns like that:
?(pattern-list) Matches zero or one occurrence of the given patterns
*(pattern-list) Matches zero or more occurrences of the given patterns
+(pattern-list) Matches one or more occurrences of the given patterns
@(pattern-list) Matches one of the given patterns
!(pattern-list) Matches anything except one of the given patterns
在 Wiki Bash Hackers 和 LinuxJournal.
这篇关于使用负前瞻错误返回 2 的 Bash 双括号正则表达式比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!