gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:30:29 25 4
gpt4 key购买 nike

在字符串匹配后插入计数器

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

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

"The Apollo program was conceived early in 1960"

看起来像:
"The Apo1llo2 pro3gram was co4nceived early in 1960"

我想我应该将 gsubperl = TRUE 一起使用,但不知道如何使用。
string <- "The Apollo program was conceived early in 1960"

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

最佳答案

这是一个使用 gregexprregmatchesregmatches<- 强大组合的选项:

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"

关于regex - 在字符串中的正则表达式匹配后插入计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28623925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com