我有一个字符串,看起来像这样:
something-------another--thing
我想用一个破折号替换多个破折号。
因此,预期的输出将是:
something-another-thing
我们可以在这里尝试使用sub
:
x <- "something-------another--thing"
gsub("-{2,}", "-", x)
[1] "something-another-thing"
更一般地说,如果我们想用单个字符替换两个或多个相同字符的任何序列,请使用此版本:
x <- "something-------another--thing"
gsub("(.)\1+", "\1", x)
第二种模式可以使用解释:
(.) match AND capture any single letter
\1+ then match the same letter, at least one or possibly more times
然后,我们只用捕获的单个字母替换。
你可以用gsub和regex来做到这一点。
> text='something-------another--thing'
> gsub('-{2,}','-',text)
[1] "something-another-thing"
t2 <- "something-------another--thing"
library(stringr)
str_replace_all(t2, pattern = "-+", replacement = "-")
这给了:
[1] "something-another-thing"
如果您正在寻找正确的正则表达式来搜索字符串,您可以在此处进行测试 https://regexr.com/
在上面,你只是在搜索一个连字符的模式,所以pattern = "-"
,但我们添加了加号,以便搜索是"贪婪的"并且可以包含许多连字符,所以我们得到pattern = "-+"