从 R 中的正则表达式 class 中删除字符

Removing character from regexp class in R

编辑:更改整个问题以使其更清楚。

我可以从 R 中的正则表达式 类 之一(例如 [:alnum:])中删除单个字符吗?

例如,匹配除_字符之外的所有标点符号([:punct:])。

我正在尝试替换 markdown 中使用的下划线以实现斜体化,但斜体化的子字符串可能包含一个我想保留的下划线。

编辑:作为另一个例子,我想捕获下划线对之间的所有内容(注意一对包含一个我想保持在 1 到 10 之间的下划线)

This is _a random_ string with _underscores: rate 1_10 please_

你不会相信,但是 lazy matching 仅用 ? 就达到了预期效果:

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."

这是demo program

不过,如果要修改[[:print:]]class,注意基本上是[\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)

Returns

[1] "This is a string with some random underscores in it."

类似于@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"

这里我们使用词边界和延迟匹配。请注意,默认的正则表达式引擎在惰性重复和捕获组方面存在问题,因此您可能需要使用 perl=T

gsub('(?<=\D)\_(?=\D|$)','',str,perl=T)