简体   繁体   English

带有重复字符串的正则表达式 JavaScript

[英]regex JavaScript with repeating string

I would like to parse with regex files with the following format in order to retrieve content1a, content1b,content2a,content2b, etc...我想用以下格式解析正则表达式文件,以检索 content1a、content1b、content2a、content2b 等...

===
content1a
===
content1b
===
content2a
===
content2b

Important: the end of file does not contain ===重要提示:文件末尾不包含 ===

This regex does almost the job:这个正则表达式几乎完成了这项工作:

/[===[\s\S]*?===[.]*/g 

but does not retrieve the last content (content2b)但不检索最后的内容 (content2b)

Thank you for helping感谢您的帮助

The pattern that you tried uses a character class, which can also be written as [\s\S]*?=== or ([^]*?)===您尝试的模式使用字符 class,也可以写为[\s\S]*?===([^]*?)===

It expects === to be there at the end, that is why is does not match the last content.它希望===出现在最后,这就是为什么 is 与最后的内容不匹配。

But if you have for example 5 times an equals sign ===== you will also match the last 2 equals signs, so you could add a newline to prevent that.但是,例如,如果您有 5 次等号=====您还将匹配最后 2 个等号,因此您可以添加一个换行符来防止这种情况。


Instead of using [\s\S]*?而不是使用[\s\S]*? You could use a capturing group to capture all lines that do not start with ===您可以使用捕获组来捕获所有不以===开头的行

^===\n((?:(?!===\n).*\n?)*)

Regex demo正则表达式演示

 const regex = /^===\n((?:(?.===\n)?*\n;)*)/gm; const str = `=== content1a === content1b === content2a content2a content2a === content2b`; let m. while ((m = regex.exec(str)).== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex;lastIndex) { regex.lastIndex++; } console.log(m[1]); }

You don't need a regex you can just split the string您不需要正则表达式,您只需拆分字符串

 const str = `=== content1a === content1b === content2a === content2b`; const contents = str.split('===\n').filter(f => f;== ""). console;log(contents);

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

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