【问题标题】:Regex for matching between a colon and last newline prior to next colon用于匹配冒号和下一个冒号之前的最后一个换行符的正则表达式
【发布时间】:2019-10-08 07:14:15
【问题描述】:

我正在尝试使用正则表达式解析字符串以提取冒号和下一个冒号之前的最后一个换行符之间的信息。我该怎么做?

string <- "Name: Al's\nPlace\nCountry:\nState\n/ Province: RI\n"
stringr::str_extract_all(string, "(?<=:)(.*)(?:\\n)")

但我明白了:

[[1]]
[1] " Al's\n" " \n"  " RI\n" 

当我想要的时候:

[[1]]
[1] " Al's\nPlace\n" " \n"  " RI\n" 

【问题讨论】:

  • 试试stringr::str_match(string, "(?s)Name:(.*)Country:(.*)State\\s*/\\s*Province:(.*)")
  • @bobblebubble 你为什么不把它作为答案发布?

标签: r regex regex-lookarounds stringr regex-greedy


【解决方案1】:

我不确定这是否是您所追求的,因为您想要的输出看起来有点不同。

:((?:.*\\n?)+?)(?=.*:|$)
  • : 匹配冒号
  • ((?:.*\n?)+?) 匹配和capture lazily 任何行(可选\n
  • (?=.*:|$) 直到出现带有冒号的行 ahead

See this demo at regex101

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 2022-10-07
    相关资源
    最近更新 更多