簡體   English   中英

正則表達式任何東西(包括換行符)到一定順序-多個子字符串JS

[英]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}).*

DEMO

> 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM