我正在清理 R 中的文本字符串。我想删除所有标点符号except撇号和连字符。这意味着我无法使用[:punct:]
字符类(除非有一种说法[:punct:] but not '-
).
! " # $ % & ( ) * + , . / : ; < = > ? @ [ \ ] ^ _ { | } ~.
并且反引号必须出来。
对于上述大多数情况,转义不是问题。但对于方括号,我确实遇到了问题。这是我尝试过的:
gsub('[abc]', 'L', 'abcdef') #expected behaviour, shown as sanity check
# [1] "LLLdef"
gsub('[[]]', 'B', 'it[]') #only 1 substitution, ie [] treated as a single character
# [1] "itB"
gsub('[\[\]]', 'B', 'it[]') #single escape, errors as expected
错误:“[”是以“'[[”开头的字符串中无法识别的转义符
gsub('[\\[\\]]', 'B', 'it[]') #double escape, single substitution
# [1] "itB"
gsub('[\\]\\[]', 'B', 'it[]') #double escape, reversed order, NO substitution
# [1] "it[]"
我不想使用fixed=TRUE
with gsub
因为这会阻止我使用字符类。那么,如何在正则表达式字符类中包含方括号?
预计到达时间额外试验:
gsub('[[\\]]', 'B', 'it[]') #double escape on closing ] only, single substitution
# [1] "itB"
gsub('[[\]]', 'B', 'it[]') #single escape on closing ] only, expected error
错误:']' 是以“'[[]”开头的字符串中无法识别的转义符
ETA:单次替换是由于未设置造成的perl=T
in my gsub
来电。 IE:
gsub('[[\\]]', 'B', 'it[]', perl=T)