【问题标题】:Why can't string literals be used in bash regular expression tests?为什么不能在 bash 正则表达式测试中使用字符串文字?
【发布时间】:2011-07-12 14:10:18
【问题描述】:

为什么下面的 bash 脚本只打印出variable worked

#! /bin/bash

foo=baaz
regex='ba{2}z'

if [[ $foo =~ 'ba{2}z' ]]; then
    echo "literal worked"
fi

if [[ $foo =~ $regex ]]; then
    echo "variable worked"
fi

bash 文档中是否有说明 =~ 运算符仅适用于变量,而不适用于文字?此限制是否适用于任何其他运营商?

【问题讨论】:

  • 如果相关,我在 Natty Narwhal 上运行 GNU bash, version 4.2.8(1)-release (x86_64-pc-linux-gnu)

标签: regex string bash variables literals


【解决方案1】:

您不再需要 bash 正则表达式的引号:

#! /bin/bash

foo=baaz
regex='ba{2}z'

if [[ $foo =~ ba{2}z ]]; then
    echo "literal worked"
fi

if [[ $foo =~ $regex ]]; then
    echo "variable worked"
fi

# Should output literal worked, then variable worked

我不记得是哪个版本改变了这一点。

【讨论】:

  • 如果字符串 lliteral 包含空格,则只有第二个选项有效
【解决方案2】:

在 Bash 3.1 之前,您的代码实际上可以正常工作。 但是从 Bash 3.2 开始,模式匹配运算符的行为发生了变化。引用最新Bash Manual

“模式的任何部分都可以被引用来强制它被匹配为 字符串。”

这正是这里发生的事情。您的意思是使用 {} 作为元字符,但由于您引用了它,Bash 会按字面意思解释它们。 你有两个选择。:

1.你可以像这样用shopt -s compat31打开3.1兼容模式:

#!/bin/bash
shopt -s compat31

foo=baaz
regex='ba{2}z'

if [[ $foo =~ 'ba{2}z' ]]; then
    echo "literal worked"
fi

if [[ $foo =~ $regex ]]; then
    echo "variable worked"
fi

2.您可以通过删除运算符右侧的引号来移植您的代码:

#!/bin/bash

foo=baaz
regex='ba{2}z'

if [[ $foo =~ ba{2}z ]]; then
    echo "literal worked"
fi

if [[ $foo =~ $regex ]]; then
    echo "variable worked"
fi

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多