您可以使用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"