一个特定的字符串可以包含我试图匹配的模式的多个实例。例如,如果我的模式是<N(.+?)N>
,我的字符串是"My name is <N Timon N> and his name is <N Pumba N>"
,那么有两个匹配项。我想用包含替换匹配项的索引的替换项替换每个匹配项。
所以在我的字符串中"My name is <N Timon N> and his name is <N Pumba N>"
,我想将字符串更改为 read "My name is [Name #1] and his name is [Name #2]"
。
我如何做到这一点,最好是用一个单一的功能?并且最好使用来自stringr
或 的函数stringi
?
您可以使用gregexpr
和regmatches
在 Base R 中执行此操作:
my_string = "My name is <N Timon N> and his name is <N Pumba N>"
# Get the positions of the matches in the string
m = gregexpr("<N(.+?)N>", my_string, perl = TRUE)
# Index each match and replace text using the indices
match_indices = 1:length(unlist(m))
regmatches(my_string, m) = list(paste0("[Name #", match_indices, "]"))
结果:
> my_string
# [1] "My name is [Name #1] and his name is [Name #2]"
笔记:
如果同一匹配项出现多次,则此解决方案将其视为不同的“名称”。例如以下内容:
my_string = "My name is <N Timon N> and his name is <N Pumba N>, <N Timon N> again"
m = gregexpr("<N(.+?)N>", my_string, perl = TRUE)
match_indices = 1:length(unlist(m))
regmatches(my_string, m) = list(paste0("[Name #", match_indices, "]"))
输出:
> my_string
[1] "My name is [Name #1] and his name is [Name #2], [Name #3] again"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句