使用bash正则表达式匹配一行

时间:2014-04-15 13:21:04

标签: regex bash

我想匹配一个包含单词但在其中没有分号的行

这应该匹配:

class test

这不应该匹配

class test;

这不应该匹配

class test; // test class

这是我期待的工作,但事实并非如此:

pattern="class [^;]*"

if [[ $line =~ $pattern ]]

感谢

4 个答案:

答案 0 :(得分:3)

您的正则表达式不是anchored,这意味着[^;]*仍将匹配所有可能;的字符(因此整体匹配)。如果你将正则表达式锚定在该行的末尾([^;]*$),它将产生你所追求的结果:

$ 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

匹配你的正则表达式,即使字符串包含分号,这就是它总是匹配的原因。如果没有分号直到字符串的最后,锚点确保正则表达式只匹配。

答案 1 :(得分:1)

直截了当地说:

 pattern="^[^;]*\bclass\b[^;]*$"
添加了

\b字边界,仅匹配xxx class xxx,不匹配superclass xxx

答案 2 :(得分:0)

使用^[^;]+($|\s*//)。这意味着从字符串的开头到行的末尾或任意数量的空格后跟两个斜杠的任意数量的非分号字符(至少一个)。

http://rubular.com/r/HTizIXz2HA

答案 3 :(得分:0)

我认为你需要:

pattern="^[^;]*class [^;]*$"`

这确保了生产线没有;在[^;]*匹配之前或之后。