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

Regex 使用bash正则表达式匹配一行,regex,bash,Regex,Bash,我想匹配一个包含单词但没有分号的行 这应符合: class test 这不应该匹配 class test; 这两者也不应该匹配 class test; // test class 这是我期待的工作,但它没有: pattern="class [^;]*" if [[ $line =~ $pattern ]] 谢谢使用^[^;]+($|\s*/)。这意味着从字符串开始到行尾的任意数量的非分号字符(至少一个),或后跟两个斜杠的任意数量的空格 我认为您需要: pattern="^[^;]*cl

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

这应符合:

class test
这不应该匹配

class test;
这两者也不应该匹配

class test; // test class
这是我期待的工作,但它没有:

pattern="class [^;]*"

if [[ $line =~ $pattern ]]
谢谢

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

我认为您需要:

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

这样可以确保线路没有故障;在你的
[^;]*
匹配之前或之后。

直接说:

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

\b
添加了单词边界,仅用于匹配
xxx类xxx
,不匹配
超类xxx
您的正则表达式不匹配,这意味着
[^;]*
仍将匹配所有字符,直到可能的
(因此作为一个整体匹配)。如果您将正则表达式锚定在行的末尾(
[^;]*$
),它将生成您想要的结果:

$ 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
TL;DR:换句话说,中的粗体部分

课堂测试;富巴库


匹配正则表达式,即使字符串包含分号,这也是它始终匹配的原因。锚点确保正则表达式仅在字符串末尾没有分号时匹配。

关于
class test//test class?不要用新问题编辑此问题,也不要删除此问题中有答案的详细信息。使用按钮并发布新问题
$ ./t.sh
testing 'class test': matches
testing 'class test;': doesn't match
testing 'class test; // test class': doesn't match