【问题标题】:Why does the POSIX "printable characters" class not match a simple string?为什么 POSIX “可打印字符”类与简单字符串不匹配?
【发布时间】:2012-04-28 07:49:41
【问题描述】:

我编写了以下脚本来测试“可打印字符”字符类,如here 所述。

#!/bin/sh

case "foo" in
    *[:print:]*) echo "found a printable character" ;;
    *) echo "found no printable characters" ;;
esac

我希望这个脚本能够输出found a printable character"foo" 中的至少一个(实际上是所有)字符是可打印的。相反,它输出"found no printable characters"。为什么"foo" 中的字符不能被识别为可打印字符?

【问题讨论】:

    标签: regex linux shell posix non-printable


    【解决方案1】:

    字符串[:只是特殊的括号表达式中,括号表达式本身是由[引入的。所以你的例子应该是:

    case "foo" in
        *[[:print:]]*) echo "found a printable character" ;;
        *) echo "found no printable characters" ;;
    esac
    

    如果这看起来很麻烦,请考虑例如如何指定一个模式,该模式应该匹配小写字母或数字但不匹配大写字母。

    有关详细信息,请参阅section of the POSIX spec detailing bracket expressions in regular expressions。 shell 模式中的括号表达式与正则表达式中的括号表达式类似,除了对!^ 的处理。 (尽管在括号表达式的上下文之外,shell 模式和正则表达式之间还有其他区别)。

    【讨论】:

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