【问题标题】:Why does this regex in bash not match the line despite matching in regex tester? [duplicate]尽管在正则表达式测试器中匹配,为什么 bash 中的这个正则表达式与该行不匹配? [复制]
【发布时间】:2019-07-31 00:34:48
【问题描述】:

我正在尝试匹配netstat 中的一行,其中本地端口与传递给我的脚本的某个端口匹配。但是这个正则表达式(虽然它在正则表达式测试器中匹配)似乎不起作用。

# Get lines from netstat
IFS=$'\r\n' GLOBIGNORE='*' command eval  'NetstatLines=($(netstat -anq))'

for line in "${NetstatLines[@]}"; do

    # This never matches
    if [[ "$line" =~ ^\s*(TCP|UDP)\s+(\d+\.\d+\.\d+\.\d+:$iPort|\[::\d*\]:$iPort)\s+ ]]; then
        echo "found it!!"
    fi

done

线条看起来像:

Active Connections

  Proto  Local Address          Foreign Address        State
  TCP    0.0.0.0:135            0.0.0.0:0              LISTENING
  TCP    0.0.0.0:445            0.0.0.0:0              LISTENING
  TCP    0.0.0.0:623            0.0.0.0:0              LISTENING
  TCP    0.0.0.0:2179           0.0.0.0:0              LISTENING
  TCP    0.0.0.0:5040           0.0.0.0:0              LISTENING
  TCP    0.0.0.0:7680           0.0.0.0:0              LISTENING

所以如果$iPort135,它应该匹配第 4 行。

【问题讨论】:

  • Bash 使用 posix ERE,而不是 Perl 风格的那种。
  • @Shawn 我在哪里可以找到有关该语法和测试人员的信息?
  • 只要搜索“posix扩展正则表达式”,你会发现很多。
  • @Shawn 我做到了,但我找不到有关如何将当前正则表达式转换为 posix 的足够信息。
  • POSIX RE 语法不支持\d\s 快捷方式;请改用[[:digit:]][[:space:]]

标签: regex bash shell sh mingw


【解决方案1】:

感谢@Shawn 和这些网站:

我想通了:

^[[:space:]]*(TCP|UDP)[[:space:]]+([[:digit:]]+[.][[:digit:]]+[.][[:digit:]]+[.][[:digit:]]+:$iPort|[[]::[[:digit:]]*[]]:$iPort)

这相当于我开始使用的非 posix 版本。

【讨论】:

    猜你喜欢
    • 2013-04-19
    • 2020-01-25
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多