编辑:改变整个问题,使它更清楚。
我能否从R中的一个正则表达式类(如[:alnum:]
)中删除一个字符?
例如,匹配除[:punct:]
字符以外的所有标点符号( _
)。
我正在尝试用于斜体化的替换下划线,但是斜体子字符串可能包含一个我希望保留的下划线。
编辑:另一个例子是,我想捕捉每对下划线之间的所有内容(注意,一对下划线包含一个单独的下划线,我希望保持在1到10之间)
This is _a random_ string with _underscores: rate 1_10 please_
发布于 2015-05-18 15:02:52
您可能不会相信,但是懒惰匹配仅仅是用?
实现的,就像这里所期望的那样:
str <- 'This is a _string with_ some _random underscores_ in it.'
gsub("_+([[:print:]]+?)_+", "\\1", str)
str <- 'This is a _random string with_ a scale of 1_10.'
gsub("_+([[:print:]]+?)_+", "\\1", str)
结果:
[1] "This is a string with some random underscores in it."
[1] "This is a random string with a scale of 1_10."
这是演示程序
但是,如果您想修改[[:print:]]
类,请记住,它基本上是一个[\x20-\x7E]
范围。下划线为\x5F
,您可以轻松地将其排除在范围之外,并使用[\x20-\x5E\x60-\x7E]
。
str <- 'This is a _string with_ some _random underscores_ in it.'
gsub("_+([\x20-\x5E\x60-\x7E]+)_+", "\\1", str)
[1] "This is a string with some random underscores in it."
发布于 2015-05-18 15:06:15
类似@stribizhev:
x <- "This is _a random_ string with _underscores: rate 1_10 please_"
gsub("\\b_(.*?)_\\b", "\\1", x, perl=T)
生产:
[1] "This is a random string with underscores: rate 1_10 please"
在这里,我们使用单词边界和懒惰匹配。请注意,默认的regexp引擎存在延迟重复和捕获组的问题,因此您可能需要使用perl=T
。
发布于 2015-05-18 15:07:39
gsub('(?<=\\D)\\_(?=\\D|$)','',str,perl=T)
https://stackoverflow.com/questions/30313460
复制