替换匹配后的字符串部分

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

r - replace part of string after its matched

问题

我想替换一个字符串的一部分,该部分如以下示例所示:

str1 <- "abc sdak+ 123+"

我想替换所有在3个数字之后出现的+,但不替换在字符后出现的+。我尝试过这样,但这替换了整个匹配的字符串,而我只想将+替换为-

gsub("[0-9]{3}\\+", "-", str1)

期望的结果应该是:

"abc sdak+ 123-"
英文:

i'm trying to replace a part of a string which is matched like in the following example:

str1 &lt;- &quot;abc sdak+ 123+&quot;

I would like to replace all + that come after 3 numbers, but not in the case when a + is coming after characters. I tried like this, but this replaces the whole matched string, when I only want to replace the + with a -

gsub(&quot;[0-9]{3}\\+&quot;, &quot;-&quot;, str1)

The desired outcome should be:

"abc sdak+ 123-"

答案1

得分: 2

可以捕获这3个数字作为一个组((...))以及+,然后用捕获组的反向引用(\\1)和-来替换它。只需确保在这3个数字之前没有其他数字,可以使用单词边界(\\b)或空格(\\s)。

gsub("\\b(\\d{3})\\+", "\-", str1)

输出

[1] "abc sdak+ 123-"
英文:

We could capture the 3 digits as a group ((...)) and the +, replace with the backreference (\\1) of the captured group and the -. Just to make sure that there is no digits before the 3 digits, use either word boundary (\\b) or a space (\\s)

 gsub(&quot;\\b(\\d{3})\\+&quot;, &quot;\-&quot;, str1)

-output

[1] &quot;abc sdak+ 123-&quot;

答案2

得分: 2

你也可以使用look-behind,即是否在3个数字之前有+符号?如果是的话,替换它。

str1 <- "abc sdak+ 123+"
gsub("(?<= [0-9]{3})\\+", "-", str1, perl = TRUE)
[1] "abc sdak+ 123-"
英文:

You can also use look-behind ie is the + symbol preceded by 3 numbers? if so, replace it.

str1 &lt;- &quot;abc sdak+ 123+&quot;
gsub(&quot;(?&lt;= [0-9]{3})\\+&quot;, &quot;-&quot;, str1, perl = TRUE)
[1] &quot;abc sdak+ 123-&quot;

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

发表评论

匿名网友

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

确定