在字符串中正则表达式匹配后插入计数器

前端之家收集整理的这篇文章主要介绍了在字符串中正则表达式匹配后插入计数器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在字符串匹配后插入计数器

我试图在字符串中的每个匹配后插入一个计数后缀.

例如:在以下字符串中每个匹配的“o”之后插入一个数字:

"The Apollo program was conceived early in 1960"

看起来像:

"The Apo1llo2 pro3gram was co4nceived early in 1960"

我想我应该使用gsub可能与perl = TRUE,但不知道如何.

string <- "The Apollo program was conceived early in 1960"

gsub( x = string,pattern = "(o)",replacement = "\\1 $count",perl = TRUE )

解决方法

这是一个使用gregexpr,regmatches和regmatches< - 的强大组合的选项:

x <- c("The Apollo program was conceived early in 1960","The International Space Station was launched in 1998")

m <- gregexpr("(?<=o)",x,perl=TRUE)
regmatches(x,m) <- lapply(regmatches(x,m),seq_along)

x
# [1] "The Apo1llo2 pro3gram was co4nceived early in 1960"    
# [2] "The Internatio1nal Space Statio2n was launched in 1998"

猜你在找的正则表达式相关文章