【问题标题】:How to extract a select set of characters between delimiters如何在分隔符之间提取一组选定的字符
【发布时间】: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>")

我需要提取那些 &lt;rep&gt; ... &lt;/rep&gt; 分隔符内的数字。另外一个困难是我不想提取其他数字,每个数字前面都有{[

想要的输出是这样的:

"1212" "2" "13" "12"

删除不需要的数字很容易,即使用嵌入的 gsub 替换,但将提取限制在 &lt;rep&gt; ... &lt;/rep&gt; 分隔符之间的数字要困难得多。我的预感是后瞻和前瞻将成为解决方案的一部分。我不清楚如何实施它们。这是我尝试过的,但很不完美:

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


【解决方案1】:

您可以先用gsub 替换以[{ 开头的不感兴趣的数字。然后使用gregexprregmatches提取&lt;rep&gt;&lt;/rep&gt;之间的部分,然后再次使用gsub删除所有不是数字的部分。

x <- gsub("(\\{|\\[)\\d+", "", reps)
unlist(lapply(regmatches(x, gregexpr("<rep>.*?</rep>", x)),
  gsub, pattern="\\D", replacement=""))
#[1] "1212" "2"    "13"   "12"  

【讨论】:

  • 感谢您的回复。只有一个问题:如何更改解决方案才能将第二个字符串的两个结果粘贴在一起,如下所示:"1212" "2, 13" "12"
  • 试试:sapply(lapply(regmatches(x, gregexpr("&lt;rep&gt;.*?&lt;/rep&gt;", x)), gsub, pattern="\\D", replacement=""), paste, collapse = ", ")
猜你喜欢
  • 2023-03-10
  • 2011-12-02
  • 1970-01-01
  • 2018-10-13
  • 1970-01-01
  • 1970-01-01
  • 2012-11-27
  • 2012-08-18
  • 1970-01-01
相关资源
最近更新 更多