在字符串中正则表达式匹配后插入计数器
发布时间:2020-12-14 06:04:57 所属栏目:百科 来源:网络整理
导读:在字符串匹配后插入计数器 我试图在字符串中的每个匹配后插入一个计数后缀. 例如:在以下字符串中每个匹配的“o”之后插入一个数字: "The Apollo program was conceived early in 1960" 看起来像: "The Apo1llo2 pro3gram was co4nceived early in 1960"
在字符串匹配后插入计数器
我试图在字符串中的每个匹配后插入一个计数后缀. 例如:在以下字符串中每个匹配的“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" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容