加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 17:02:16 所属栏目:安全 来源:网络整理
导读:我想匹配包含单词的行,但不包含分号 这应该匹配: class test 这应该不匹配 class test; 这也不应该匹配 class test; // test class 这是我期待的工作,但它没有: pattern="class [^;]*"if [[ $line =~ $pattern ]] 谢谢 你的正则表达式不是 anchored ,这意
我想匹配包含单词的行,但不包含分号

这应该匹配:

class test

这应该不匹配

class test;

这也不应该匹配

class test; // test class

这是我期待的工作,但它没有:

pattern="class [^;]*"

if [[ $line =~ $pattern ]]

谢谢

你的正则表达式不是 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:换句话说,大胆的部分

class test; foo bar quux

匹配你的正则表达式,即使字符串包含分号,这就是它总是匹配的原因.锚点确保正则表达式只有在字符串的最后没有分号时才匹配.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读