【问题标题】:Regex between two characters and over multiple lines两个字符之间和多行之间的正则表达式
【发布时间】:2020-01-13 22:13:12
【问题描述】:

我这里有这个字符串:

-Node: song
--Tag: ItsyWitsySpider
---lyrics: The itsy witty spider climbed up the waterspout.
       Down came the rain,
       and washed the spider out
--Tag: BaBaBlackSheep
---lyrics: Baa, baa, black sheep, have you any wool?
       Yes sir, yes sir, three bags full!
       One for the master,
       And one for the dame,
--Tag:IfYoureHappyAndYouKnowIt
...

我想得到所有的

       The itsy witty spider climbed up the waterspout.
       Down came the rain,
       and washed the spider out

通过使用正则表达式 到目前为止,我最好的正则表达式是:

(?<=ItsyWitsySpider\n)(?:_*lyrics: ).*?(?=_)

在这里试穿:https://regex101.com/r/3myZwB/1 它似乎不起作用 感谢您的帮助

【问题讨论】:

    标签: regex


    【解决方案1】:

    您可以扩展lookbehind并确保在换行符后匹配连字符:

    (?<=ItsyWitsySpider\n---lyrics: ).*?(?=\r?\n-)
    

    说明

    • (?&lt;= 正面向后看,断言左边是
      • ItsyWitsySpider\n---lyrics: 匹配ItsyWitsySpider,换行符和---lyrics:
    • ) 近距离正面观察
    • .*? 匹配除换行符以外的任何字符,非贪心
    • (?= 正向前瞻,断言左边是
      • \r?\n- 匹配换行符,然后匹配 -
    • ) 关闭前瞻

    Regex demo


    或者您可以使用捕获组而不是后向查找,这样可以更有效地匹配所有不以 --Tag 开头的行。

    ItsyWitsySpider\r?\n---lyrics: (.*(?:\r?\n(?!--Tag).*)*)\r?\n--Tag
    

    部分

    • ItsyWitsySpider\r?\n---lyrics: 匹配 ItsyWitsySpider 直到 lyrics:
    • ( 捕获第 1 组
      • .* 匹配除换行符以外的任何字符 0+ 次
      • (?:非捕获组
        • \r?\n(?!--Tag) 匹配换行符并断言下一行不以--Tag 开头
        • .* 匹配除换行符以外的任何字符 0+ 次
      • )*关闭组重复0+次
    • )关闭第一组
    • \r?\n--Tag 匹配换行符,后跟 --Tag

    Regex demo

    【讨论】:

    • @makingAMess 请为答案投票,而不是离开谢谢 cmets。
    • @jrook 遗憾的是我没有足够的代表编辑:看起来我现在有:-D
    • @第四只鸟的解释也很好
    • @makingAMess 感谢他人帮助您的最佳方式是pay it forward
    【解决方案2】:

    您的文本包含连字符-,但您的正则表达式查找下划线_。你的正则表达式应该是

    (?<=ItsyWitsySpider\n)(?:-*lyrics: ).*?(?=-)
    

    虽然一个更快的正则表达式会是

    (?<=ItsyWitsySpider\n)(?:_*lyrics: )[^-]*
    

    【讨论】:

    • 最后用了第四只鸟和你的一点点??
    【解决方案3】:
    /The itsy.*([\r\n].*)*out/gm
    

    let re = /The itsy.*([\r\n].*)*out/gm
    let str = `
          -Node: song
          --Tag: ItsyWitsySpider
          ---lyrics: The itsy witty spider climbed up the waterspout.
                 Down came the rain,
                 and washed the spider out
          --Tag: BaBaBlackSheep
          ---lyrics: Baa, baa, black sheep, have you any wool?
                 Yes sir, yes sir, three bags full!
                 One for the master,
                 And one for the dame,
          --Tag:IfYoureHappyAndYouKnowIt
    ...
    `
    
    console.log(str.match(re))

    【讨论】:

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