【问题标题】:Match text(a..b) from the last occurrence of a word(a) till first occurrence of another word(b)匹配文本(a..b)从最后一次出现的单词(a)到第一次出现的另一个单词(b)
【发布时间】:2014-07-03 16:40:18
【问题描述】:

对以下输入使用正则表达式:

输入

response {
   id: 1
   files: 1.bin
   major: 338013710701
   status: Received
}
response {
   id: 1
   files: 1.bin
   major: 35723057325
   status: Valid
}
response {
   id: 1
   files: 1.bin
   major: 27151510570
   status: Accepted
}

我期待匹配的输出:

预期输出

response {
   id: 1
   files: 1.bin
   major: 27151510570
   status: Accepted

其中id: 1 是匹配项所必需的。我尝试使用以下正则表达式:

/response {\n {3}id: 1.*?status: Accepted/m

它从第一个 responsestatus: Accepted 进行选择。任何人都可以帮助构建正确的正则表达式以匹配预期的输出吗?

【问题讨论】:

    标签: ruby regex


    【解决方案1】:

    您可以尝试以下正则表达式来匹配包含字符串 status: Accepted 的响应块,

    /response\s*\{\n[^\n]*\n[^\n]*\n[^\n]*\n\s*status: Accepted/m
    

    DEMO

    说明:

    • response 匹配文字字符串响应。
    • \s* Zeror 或更多空格。
    • { 文字 { 符号。
    • \n 匹配换行符。
    • [^\n]* 匹配任何非换行符零次或多次的字符。
    • \n 匹配换行符。
    • [^\n]* 匹配任何非换行符零次或多次的字符。
    • \n\s* 换行符和零个或多个空格。
    • status: Accepted 匹配字符串 status: Accepted

    更新:

    你也可以使用这个正则表达式,

    /response {[\s\n\w\.:]*id:\s*1[\s\n\w\.:]*status: Accepted/m
    

    DEMO

    【讨论】:

    • 你能解释一下上面的表达式是做什么的吗?
    • 我稍微修改了输入并尝试了相同的方法。我在匹配第 19 行到第 25 行的块时遇到了一些问题。您可以在以下链接中查看它吗rubular.com/r/BYC4dD6tp8
    • 你想要上面评论的答案吗?
    【解决方案2】:

    使用这个:

    /(.*(response.*?status: Accepted))/s
    

    你会在第二个反向引用中得到它

    \2$2

    在这里演示:http://regex101.com/r/aO2qD8/1

    【讨论】:

      猜你喜欢
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多