[英]Regex anything(including new lines) up to certain sequence - multiple substrings JS
我正在尝试处理的文件如下所示:
...
...
15 Apr 2014 22:05 - id: content
15 Apr 2014 22:09 - id: content
15 Apr 2014 22:09 - id: content
with new line
16 Apr 2014 06:56 - id: content
with new line
with new line
16 Apr 2014 06:57 - id: content
16 Apr 2014 06:58 - id: content
...
...
我想出的正则表达式是: \\d{1,}[ ][AZ][az]{2}[ ](?:\\d{4}[ ]\\d{2}[:]\\d{2}|\\d{2}[:]\\d{2}).*
结果是:
这几乎是对的,我只需要包含换行符,但是如果我包含此[\\s\\S]*
而不是.*
仅返回一个匹配项。
我想提取的是一组子字符串,其中每个字符串都以数据序列开始,并以下一个日期序列结束,如下所示:
...
...
15 Apr 2014 22:05 - id: content //substring 1
15 Apr 2014 22:09 - id: content //substring 2
15 Apr 2014 22:09 - id: content //substring 3
with new line //substring 3
16 Apr 2014 06:56 - id: content //substring 4
with new line //substring 4
with new line //substring 4
16 Apr 2014 06:57 - id: content //substring 5
16 Apr 2014 06:58 - id: content //substring 6
...
...
有什么帮助我失踪吗?
您需要使用肯定的前瞻性断言。
\d{1,}[ ][A-Z][a-z]{2}[ ](?:\d{4}[ ]\d{2}[:]\d{2}|\d{2}[:]\d{2})[\s\S]*?(?:(?!\n\n)[\s\S])*?(?=\n\d{1,}[ ])|\d{1,}[ ][A-Z][a-z]{2}[ ](?:\d{4}[ ]\d{2}[:]\d{2}|\d{2}[:]\d{2}).*
> var str = '...\n...\n15 Apr 2014 22:05 - id: content\n15 Apr 2014 22:09 - id: content\n15 Apr 2014 22:09 - id: content\nwith new line\n16 Apr 2014 06:56 - id: content\nwith new line\nwith new line\n16 Apr 2014 06:57 - id: content\n\n16 Apr 2014 06:58 - id: content\n...\n...';
undefined
> var re = /\d{1,}[ ][A-Z][a-z]{2}[ ](?:\d{4}[ ]\d{2}[:]\d{2}|\d{2}[:]\d{2})[\s\S]*?(?:(?!\n\n)[\s\S])*?(?=\n\d{1,}[ ])|\d{1,}[ ][A-Z][a-z]{2}[ ](?:\d{4}[ ]\d{2}[:]\d{2}|\d{2}[:]\d{2}).*/gm;
undefined
> str.match(re)
[ '15 Apr 2014 22:05 - id: content',
'15 Apr 2014 22:09 - id: content',
'15 Apr 2014 22:09 - id: content\nwith new line',
'16 Apr 2014 06:56 - id: content\nwith new line\nwith new line',
'16 Apr 2014 06:57 - id: content\n',
'16 Apr 2014 06:58 - id: content' ]
请参阅此处的第二个答案: 如何在多行中使用JavaScript正则表达式?
尝试使用非贪婪量词[\\ s \\ S]? 这样,看看它返回什么。 或者,只需返回一个输出,然后在换行符上拆分整个字符串即可...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.