简体   繁体   English

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

[英]Why does the POSIX “printable characters” class not match a simple string?

I wrote the following script to test the "printable characters" character class, as described here . 我写了下面的脚本来测试“可打印字符”字符类,如所描述这里

#!/bin/sh

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

I expect this script to output found a printable character , at least one (in fact, all) characters in "foo" are printable. 我希望这个脚本输出found a printable character"foo"中至少有一个(实际上是所有)字符是可打印的。 Instead, it outputs "found no printable characters" . 相反,它输出"found no printable characters" Why are the characters in "foo" not recognized as printable characters? 为什么"foo"中的字符不被识别为可打印字符?

The string [: is only special inside a bracket expression and bracket expressions are themselves introduced by [ . 字符串[:括号表达式中是特殊的,括号表达式本身由[引入[ So your example should be: 所以你的榜样应该是:

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

If this seems cumbersome, think about for example how you would specify a pattern which should match a lowercase letter or a digit but not an upper case letter. 如果这看起来很麻烦,请考虑一下如何指定一个应该匹配小写字母或数字而不是大写字母的模式。

For more information see the section of the POSIX spec detailing bracket expressions in regular expressions . 有关更多信息,请参阅正则表达式中详细说明括号表达式的POSIX规范部分 Bracket expressions in shell patterns are like bracket expressions in regular expressions, except for the treatment of ! shell模式中的Bracket表达式就像正则表达式中的括号表达式一样,除了处理! and ^ . ^ (Though otherwise there are other differences between shell patterns and regexes, outside the context of bracket expressions). (尽管在括号表达式的上下文之外,shell模式和正则表达式之间存在其他差异)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM