使用 stringr 删除两个或更多连续的字符

huangapple go评论50阅读模式
英文:

Remove two or more consecutive characters using stringr

问题

我试图删除脚本中任何具有2个或更多连续ticks的时间。我从这里知道可以使用正则表达式(.)\1来检测任何重复字符,所以我将其修改为(`)\1,但这不起作用。为什么不起作用?

library(stringr)
example <- c("``", "````", "`")
str_replace_all(example, "(`)\", "gone") #希望前两个变成'gone',第三个保持不变
英文:

I'm trying to remove any time my script has 2 or more consecutive ticks. I know from here that using regex you can detect any repeating characters with (.)\1, so I modified it to (`)\1 but that doesn't work. Why not?

library(stringr)
example &lt;- c(&quot;``&quot;, &quot;````&quot;, &quot;`&quot;)
str_replace_all(example, &quot;(`)&quot;, &quot;gone&quot;) #want the first 2 to say &#39;gone&#39; and the 3rd to stay the same

答案1

得分: 3

library(stringr)
example &lt;- c(&quot;``&quot;, &quot;````&quot;, &quot;`&quot;)

# 移除连续出现的一对
str_replace_all(example, &quot;(``)+&quot;, &quot;gone&quot;) 

# 移除两个或更多连续的``
str_replace_all(example, &quot;``+&quot;, &quot;gone&quot;) 
英文:
library(stringr)
example &lt;- c(&quot;``&quot;, &quot;````&quot;, &quot;`&quot;)

# THIS removes consecutives in pairs
str_replace_all(example, &quot;(``)+&quot;, &quot;gone&quot;) 

# THIS removes two or more consecutive
str_replace_all(example, &quot;``+&quot;, &quot;gone&quot;) 

</details>



huangapple
  • 本文由 发表于 2023年2月7日 02:03:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75364977.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定