javascript - JS : matching entries with capture groups, 占新行

标签 javascript regex

鉴于此文本:

1/12/2011
I did something.

10/5/2013
I did something else.

Here is another line.

And another.

5/17/2014
Lalala.
More text on another line.

我想使用正则表达式(或者其他方式?)来得到这个:

["1/12/2011", "I did something.", "10/5/2013", "I did something else.\n\nHere is another line.\n\nAnd another.", "5/17/2014", "Lalala.\nMore text on another line."]

日期部分内容部分都是单独的条目,交替出现。

我尝试使用 [^] 而不是点,因为 JS 的 .* 不匹配新行(如 Matching multiline Patterns 所说),但是匹配是贪婪的并且占用了太多,所以结果数组只有1 条记录:

var split_pattern = /\b(\d\d?\/\d\d?\/\d\d\d\d)\n([^]+)/gm;
var array_of_mems = contents.match(split_pattern);

// => ["1/12/2011↵I did something else..."]

如果我加一个问号得到[^]+?,则根据How to make Regular expression into non-greedy?使匹配非贪婪,然后我只得到内容部分的第一个字符。

最好的方法是什么?提前致谢。

最佳答案

(\d{1,2}\/\d{1,2}\/\d{4})\n|((?:(?!\n*\d{1,2}\/\d{1,2}\/\d{4})[\s\S])+)

您可以尝试这个。抓取捕获的内容。查看演示。

https://regex101.com/r/sJ9gM7/126

var re = /(\d{1,2}\/\d{1,2}\/\d{4})\n|((?:(?!\n*\d{1,2}\/\d{1,2}\/\d{4})[\s\S])+)/gim;
var str = '1/12/2011\nI did something.\n\n10/5/2013\nI did something else.\n\nHere is another line.\n\nAnd another.\n\n5/17/2014\nLalala.\nMore text on another line.';
var m;

if ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}

关于javascript - JS : matching entries with capture groups, 占新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29690512/

相关文章:

javascript - 如何用特定颜色填充整个 Canvas ?

javascript - 选择类(class)的第一个 child 在 <select> 中不起作用

javascript - 如何使用php在mysql数据库中存储文件和字段数组

JAVA:replaceAll 正则表达式模式

java - text.replaceAll ("(?i)("+ 查询 + ")", "<b>$1</b>") 与 GWT

javascript - 相同的 RegExp 交替返回 true 和 false。为什么?

javascript - 为什么 material-ui 两次调用他们的对话框?

javascript - 解析 JSON,找到值的匹配项并将其存储在数组中

javascript - 阿拉伯语语言的正则表达式

regex - 需要使用 RegEx 防止重复字符