POSIX 字符类需要包装在字符类中,正确的形式是 [[:punct:]]
. 不要将 POSIX 术语“字符类”与通常所说的正则表达式字符类混淆。
此 POSIX 命名类在 ASCII 范围内匹配所有非控件、非字母数字、非空格字符。
ascii <- rawToChar(as.raw(0:127), multiple=T)
paste(ascii[grepl('[[:punct:]]', ascii)], collapse="")
# [1] "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
虽然如果 a locale
生效,它可能会改变 [[:punct:]]
...
R 文档?regex
声明如下: 某些命名的字符类别是预定义的。它们的解释取决于语言环境(参见locales);解释是 POSIX 语言环境的解释。
punct的 Open Group LC_TYPE 定义说:
定义要分类为标点字符的字符。
在 POSIX locale<space>
中,不应包含 alpha、digit 或 cntrl 类中的 the或任何字符。
在语言环境定义文件中,不应为关键字upper、lower、alpha、digit、cntrl、xdigit 或as<space>
指定任何字符。
然而,stringi 包似乎依赖于ICU,而 locale 是 ICU 中的一个基本概念。
使用 stringi 包,我建议使用Unicode 属性\p{P}
和\p{S}
.
\p{P}
匹配任何类型的标点符号。也就是说,它缺少 POSIX 类punct包含的九个字符。这是因为 Unicode 将 POSIX 认为的标点符号分为两类,标点符号和符号。这是\p{S}
到位的地方......
stri_replace_all_regex(string1, '[\\p{P}\\p{S}]', ' ')
# [1] "this is a test" "this is also a test"
# [3] "this is the final test" "this is the final test "
或者gsub
从能够很好地处理这个问题的基础 R 回退。
gsub('[[:punct:]]', ' ', string1)
# [1] "this is a test" "this is also a test"
# [3] "this is the final test" "this is the final test "