为什么POSIX“可打印字符”类与简单字符串不匹配?

时间:2012-04-17 00:02:29

标签: regex linux shell posix non-printable

我编写了以下脚本来测试“可打印字符”字符类,如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"中的字符无法识别为可打印字符?

1 个答案:

答案 0 :(得分:8)

字符串[:只是里面括号表达式,括号表达式本身由[引入。所以你的榜样应该是:

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模式和正则表达式之间存在其他差异)。