繁体   English   中英

两个字符之间和多行之间的正则表达式

[英]Regex between two characters and over multiple lines

我在这里得到了这个字符串:

-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它似乎不起作用感谢您的帮助

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

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

解释

  • (?<=正向后视,断言左边的是
    • ItsyWitsySpider\\n---lyrics:匹配ItsyWitsySpider、换行符和---lyrics:
  • )关闭正面回顾
  • .*? 匹配除换行符以外的任何字符
  • (?=正向前瞻,断言左边的是
    • \\r?\\n-匹配换行符,然后匹配-
  • )关闭前瞻

正则表达式演示


或者,您可以使用捕获组而不是后视,这样可以更有效地匹配所有不以--Tag开头的--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+ 次
  • )关闭第 1 组
  • \\r?\\n--Tag匹配换行符后跟--Tag

正则表达式演示

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

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

虽然更快的正则表达式将是

(?<=ItsyWitsySpider\n)(?:_*lyrics: )[^-]*
/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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM