代码之家  ›  专栏  ›  技术社区  ›  Héctor van den Boorn

正则表达式匹配所有可能

  •  1
  • Héctor van den Boorn  · 技术社区  · 7 年前

    我想创建一个regex,它只匹配以“line_start”开头的行,然后匹配所有数字。

    我现在有:

    "^line_start.*?(\\d)"
    

    带着文字 "line_start 1 abc 2 def 4" 它会回来的 1 当我执行时 str_match_all("line_start 1 abc 2 def 4", "^line_start.*?(\\d)") ,因为我用问号使它不贪婪。 如果我去掉问号:

    "^line_start.*(\\d)"
    

    正则表达式调用 str_match_all("line_start 1 abc 2 def 4", "^line_start.*(\\d)") 将返回数字4。

    如何定义正则表达式,使其返回所有数字(因此1、2和4)?记住这句台词必须以 line_start 是的。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Wiktor Stribiżew    7 年前

    你可以用

    regmatches(x, gregexpr("(?:\\G(?!^)|^line_start)\\D*\\K\\d+", x, perl=TRUE))
    

    regex R demo online 是的。

    它是一个带有PCRE正则表达式的基R解决方案,匹配:

    • (?:\\G(?!^)|^line_start) -上一个成功匹配的结尾或 line_start 在字符串的开头
    • \\D* -尽可能多的非数字字符
    • \\K -match reset运算符放弃到目前为止匹配的所有文本
    • \\d+ -1+位。