英文:
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 <- "abc sdak+ 123+"
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("[0-9]{3}\\+", "-", 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("\\b(\\d{3})\\+", "\-", str1)
-output
[1] "abc sdak+ 123-"
答案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 <- "abc sdak+ 123+"
gsub("(?<= [0-9]{3})\\+", "-", str1, perl = TRUE)
[1] "abc sdak+ 123-"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论