【问题标题】:Regex matching with a wildcard与通配符匹配的正则表达式
【发布时间】:2023-03-30 15:28:01
【问题描述】:

我正在尝试检查给定字符串中是否包含.rel6.。我对 Bash 正则表达式的行为有点困惑。我在这里错过了什么?

os=$(uname -r)                        # set to string "2.6.32-504.23.4.el6.x86_64"

[[ $os =~ *el6*    ]] && echo yes     # doesn't match, I understand it is Bash is treating it as a glob expression
[[ $os =~ el6      ]] && echo yes     # matches
[[ $os =~ .el6     ]] && echo yes     # matches
[[ $os =~ .el6.    ]] && echo yes     # matches
[[ $os =~ ".el6."  ]] && echo yes     # matches
[[ $os =~ *".el6." ]] && echo yes     # * does not match - why? *
[[ $os =~ ".el6."* ]] && echo yes     # matches

re='\.el6\.'
[[ $os =~ $re      ]] && echo yes     # matches

特别是这个:

[[ $os =~ *".el6." ]] && echo yes

【问题讨论】:

  • 如果要检查.el6. 是否在字符串中,请使用[[ $os = *".el6."* ]] && echo yes。在这里,glob 模式将是 *.el6.*,您需要在这里使用 = 运算符。

标签: regex bash glob


【解决方案1】:

=~ 运算符对其左侧的字符串执行正则表达式匹配操作,其右侧的表达式模式。所以,这里所有的 RHS 都是正则表达式模式。

[[ $os =~ *el6* ]] && echo yes 不匹配,因为正则表达式是 *el6*,而 * 是量词,但您无法量化正则表达式的开头,因此它是无效的正则表达式。请注意,[[ $os =~ el6* ]] && echo yes 将打印 yes,因为 el6* 匹配 el 和 0+ 6s。

[[ $os =~ *".el6." ]] && echo yes 也有类似的问题:正则表达式是 *.el6.,它是无效的。

如果要检查.el6. 是否在字符串中,请使用[[ $os = *".el6."* ]] && echo yes。在这里,glob 模式将是 *.el6.*,您需要 = 运算符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-26
    • 2011-03-01
    • 1970-01-01
    • 2022-01-22
    • 2016-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多