使用bash正则表达式匹配行 [英] match a line using bash regex
问题描述
我想匹配包含一个单词但没有分号的行
I want to match a line that contains a word, but does not have semi-colon in it
这应该匹配:
class test
这不应该匹配
class test;
这也不应该匹配
class test; // test class
这是我期望的工作,但事实并非如此:
this is what I was expecting to work, but it doesn't:
pattern="class [^;]*"
if [[ $line =~ $pattern ]]
谢谢
推荐答案
您的正则表达式不是 anchored ,这意味着[^;]*
仍将与所有字符匹配,直到可能的;
(并因此整体匹配).如果将正则表达式锚定到行尾([^;]*$
),它将产生您想要的结果:
Your regular expression is not anchored which means that [^;]*
will still match against all characters up to a possible ;
(and thus match as a whole). If you anchor the regex against the end of the line ([^;]*$
) it will produce the results you are after:
$ cat t.sh
#!/bin/bash
pattern='class [^;]*$'
while read -r line; do
printf "testing '${line}': "
[[ $line =~ $pattern ]] && echo matches || echo "doesn't match"
done <<EOT
class test
class test;
class test; // test class
EOT
$ ./t.sh
testing 'class test': matches
testing 'class test;': doesn't match
testing 'class test; // test class': doesn't match
TL; DR :换句话说,
班级考试; foo bar quux
class test; foo bar quux
即使字符串包含分号,
也会匹配您的正则表达式,这就是为什么它总是匹配的原因.锚确保只有在字符串的末尾没有分号 时,正则表达式才匹配.
matches your regex even though the string contains a semicolon which is why it always matches. The anchor makes sure that the regular expression only matches if there is no semicolon until the very end of the string.
这篇关于使用bash正则表达式匹配行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!