【问题标题】:Extract Only the Second Instance of Pattern in Regex在正则表达式中仅提取模式的第二个实例
【发布时间】:2020-09-24 05:49:03
【问题描述】:

我正在尝试使用编程语言 R、版本 4.0.2 和 stringr 包中的正则表达式从字符串中提取模式的第二个实例。

> test_string <- "Viscocity                      S   <=0.25        S   <=0.25 Levorotatory                      S      <=21        R      <=2.5 Giminal                    S      <=1        S      <=1"

我有以下正则表达式可以提取第一个模式(专门用于左旋):

regex <- "(\\s*(?:S|R|I|N/I)(\\s*\\W*\\d*\\.?\\d?\\d?\\d?\\s*))"
str_trim(str_extract_all(test_string, glue('(?<=Levorotatory){regex}')))

这给了我输出:

"S      <=21"

但我想抓住第二种模式R &lt;=2.5 到目前为止,我已经能够使用量词提取两种模式:

regex <- "(\\s*(?:S|R|I|N/I)(\\s*\\W*\\d*\\.?\\d?\\d?\\d?\\s*)){2}"
str_trim(str_extract_all(test_string, glue('(?<=Levorotatory){regex}')))
output: "S      <=21        R      <=2.5"

这不是我想要的。

我的问题:我可以只获取正则表达式模式的第二个实例吗?

有一些类似的帖子:hereherehere,但我尝试摆弄这些解决方案没有运气。

【问题讨论】:

    标签: r regex


    【解决方案1】:

    您可以使用如下模式与str_match

    (?<=Levorotatory)(?:\s*([SRI]|N/I)\s*([^\w\s]*\d*\.?\d+)){2}
    

    请参阅regex demo。您可以控制最后与{X} 匹配的内容。详情:

    • (?&lt;=Levorotatory) - 在当前位置之前,必须有Levorotatory(注意你可以在这里使用Levorotatory
    • (?:\s*([SRI]|N/I)\s*([^\w\s]*\d*\.?\d+)){2} - 两次出现
      • \s* - 零个或多个空格
      • ([SRI]|N/I) - SRIN/I
      • \s* - 零个或多个空格
      • ([^\w\s]*\d*\.?\d+) - 除_ 之外的零个或多个标点字符、0+ 个数字、可选的. 和一个或多个数字。

    an R demo:

    library(stringr)
    pattern <- "(?<=Levorotatory)(?:\\s*([SRI]|N/I)\\s*([^\\w\\s]*\\d*\\.?\\d+)){2}";
    x <- "Viscocity                      S   <=0.25        S   <=0.25 Levorotatory                      S      <=21        R      <=2.5 Giminal                    S      <=1        S      <=1"
    results <- str_match(x, pattern)[,-1]
    results
    # => [1] "R"     "<=2.5"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-12
      • 2013-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多