【发布时间】:2021-03-16 08:09:45
【问题描述】:
我有这样的文本数据,其中字符串按分隔符分组,有些单词附有数字:
reps <- c("<#> <rep> From the <{1> <[1> 1nEw 2ROyal% <,> </[1> you can see that 1fOUntain in the Dunville 2PArk% <{2> <[2> so-it-is%@ </[2> </rep>",
"<#> <rep> <[1> That 's 2right </rep> <#> something else <rep> I 1went on my 3Own </[1> </{1> </rep>",
"<#> <exp> <[2> Oh* 2absolUtely% </[2> </{2> </exp> <#> <rep> I know <{1> <[1> every inch </[1> and% <,> <{2> <[2> 1Every nook and 2crAnny of it% </[2> </rep>")
我需要提取那些 <rep> ... </rep> 分隔符内的数字。另外一个困难是我不想提取其他数字,每个数字前面都有{ 或[。
想要的输出是这样的:
"1212" "2" "13" "12"
删除不需要的数字很容易,即使用嵌入的 gsub 替换,但将提取限制在 <rep> ... </rep> 分隔符之间的数字要困难得多。我的预感是后瞻和前瞻将成为解决方案的一部分。我不清楚如何实施它们。这是我尝试过的,但很不完美:
library(stringr)
str_extract_all(gsub("(?<=\\{|\\[)\\d", "", reps, perl = T), "(?<=<rep>)(?!</rep>).*\\d.*?(?=</rep>)")
[[1]]
[1] " From the <{> <[> 1nEw 2ROyal% <,> </[> you can see that 1fOUntain in the Dunville 2PArk% <{> <[> so-it-is%@ </[> "
[[2]]
[1] " <[> That 's 2right </rep> <#> something else <rep> I 1went on my 3Own </[> </{> "
[[3]]
[1] " I know <{> <[> every inch </[> and% <,> <{> <[> 1Every nook and 2crAnny of it% </[> "
有什么见解吗?
编辑:
stringrsolution 从@GK 的回答中得出结论:
gsub("\\D", "", unlist(lapply(gsub("(?<=\\{|\\[)\\d", "", reps, perl = T), function(x) str_extract_all(x, "<rep>.*?</rep>"))))
[1] "1212" "2" "13" "12"
【问题讨论】:
-
第三个结果不是
13而不是3吗? -
是的,绝对的,感谢您的发现!
标签: r regex regex-lookarounds