提取而不是替换 R 中的字符串

Extract instead of Replace string in R

在此字符串中:

q <- "2 t1, 1t23 xxx, 32t1, 4"

如何从 q 优雅地提取和反转结构 \d+t\d+ 得到:

c("23X1","1X32")

我知道使用以下方法将其替换为新结构非常简单:

gsub("(\d+)t(\d+)", "\2X\1", q)

但是我没有发现任何类似的东西可以执行提取而不是替换。我查看了基本函数以及 stringrstringi 包。

stringr 我几乎得到了我需要的东西:

str_extract_all(q, "(\d+)t(\d+)")

但是没有选项可以使用等同于 "\2X\1".

的东西来操作子字符串

举个例子,在 Mathematica 中,我可以使用:

StringCases[q, RegularExpression["(\d+)t(\d+)"]:> ""]

有线索吗?

这里是相关的postRegex matching everything that's not a 4 digit number

library(stringi)

apply(stri_match_all_regex(q, "([[:digit:]]+)t([[:digit:]]+)")[[1]], 1,
       function(x) x[3] %s+% "X" %s+% x[2])
## [1] "23X1" "1X32"

如果愿意,您可以使用较短的数字 class,但我已经习惯使用 POSIX 友好的版本。

备用 stringr 版本(并使用 paste0 而不是 stringi 中方便的连接运算符:

apply(stri_match_all_regex(q, "([[:digit:]]+)t([[:digit:]]+)")[[1]], 1,
       function(x) paste0(x[3:2], collapse="X"))