在bash中的if子句中使用正则表达式


10

查看以下if块:

#!/bin/bash

str="m.m"
if [[ "${str}" =~ "m\.m" ]]; then
    echo "matched"
else
    echo "not matched"
    exit 1
fi

exit 0

这应该打印“匹配”,但不是。我要去哪里错了?

Answers:


21

您需要删除正则表达式匹配项中的引号。

if [[ ${str} =~ m\.m ]]; then

从bash手册页:

[...]还有一个附加的二进制运算符=〜,其优先级与==和!=相同。使用它时,运算符右边的字符串被视为扩展的正则表达式,并进行了相应的匹配(如regex(3)中所述)。如果字符串与模式匹配,则返回值为0,否则为1。如果正则表达式在语法上不正确,则条件表达式的返回值为2。如果启用了shell选项nocasematch,则执行匹配时将不考虑字母字符的大小写。 可以引用模式的任何部分以强制将其匹配为字符串。

因此,使用引号会导致使用旧的字符串匹配。

如果您在模式中需要空格,则只需将其转义:

str="m   m"
if [[ ${str} =~ m\ +m ]]; then

但是没有双引号,我们不能在正则表达式模式中使用空格字符。有什么解决办法吗?
Majid Azimi 2012年

1
空间应该像那样逃脱\
ДМИТРИЙМАЛИКОВ

如果要查找以动态数字结尾的字符串,应该使用${str} =~ "needle"[0-9]{1}还是应该使用${str} =~ needle[0-9]{1}
mgutt
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.