Bash双括号正则表达式比较使用负前瞻错误返回2

时间:2015-06-18 01:18:12

标签: regex bash negative-lookahead square-bracket

在Bash 4.1机器上,

我正在尝试使用“双括号[[ expression ]]来使用“ NEGATIVE LOOKAHEAD ”进行REGEX比较。

我做了“set +H”以禁用BASH变量“!”扩展来命令历史记录搜索。

我想匹配“任意字符串”,“ arm-trusted-firmware ”除外。

set +H
if [[ alsa  =~ ^(?!arm-trusted-firmware).* ]]; then echo MATCH; else echo "NOT MATCH"; fi

我希望这会打印“MATCH”, 但它会打印“NOT MATCH”。

查看“双括号”的返回码后, 它返回“2”:

set +H
[[ alsa  =~ ^(?!arm-trusted-firmware).* ]]
echo $?

根据bash手册, 返回值'2'表示“正则表达式在语法上不正确”:

  

另外一个二元运算符=〜,   具有与==和!=相同的优先级   使用时,   考虑运营商右侧的字符串   一个扩展的正则表达式并相应地匹配(如正则表达式(3))   如果字符串与模式匹配,则返回值为0,否则返回1。   如果正则表达式在语法上不正确,   条件表达式的返回值是2.

我做错了什么?

在我的原始剧本中, 我正在与STRING列表进行比较。

匹配时,我会触发一些函数调用;

当它不匹配时,我会跳过我的行为。

所以,是的,从这个例子中,

我在字面上比较'alsa'和'arm-trusted-firmware'之间的STRING。

2 个答案:

答案 0 :(得分:3)

默认情况下,bash POSIX标准不支持PCRE。 (source: Wiki Bash Hackers

作为解决方法,您需要启用extglob。这将启用一些扩展的全球模式:

$ shopt -s extglob

点击Wooledge Wiki查看有关extglob的更多信息。

然后你就可以使用这样的模式:

?(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的扩展BASH通配的更多信息。

答案 1 :(得分:3)

感谢@Barmar的答案

BASH不支持" 环视" ( lookahead lookbehind

  

bash没有使用PCRE,也不支持外观