我有正则表达式:
let re = /\[(.*?)\] \[(.*?)\] \[(.*?)\] (.*)/gm;
let regex = new RegExp(re);
我的字符串:
[Max] [2017-12-12 15:59 (UTC +02:00)] [Technical issues] Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
[Corben Dallas] [2017-12-20 12:48 (UTC +02:00)] [Technical issues] Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
[Max] [2017-12-12 15:59 (UTC +02:00)] [Technical issues] Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
我需要翻阅每个人的文字。但我的问题是,文本可能包含换行符\n
,而我的正则表达式仅将文本复制到行尾。请看这里的例子https://regex101.com/r/t7zV1U/1
See regex in use here:切换到PCRE风格以查看字符串中的实际匹配。
\[([^\]]*)\] \[([^\]]*)\] \[([^\]]*)\] ((?:(?!^\[)[\s\S])*)
var s = `[Max] [2017-12-12 15:59 (UTC +02:00)] [Technical issues] Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
[Corben Dallas] [2017-12-20 12:48 (UTC +02:00)] [Technical issues] Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
[Max] [2017-12-12 15:59 (UTC +02:00)] [Technical issues] Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. `
var r = /\[([^\]]*)\] \[([^\]]*)\] \[([^\]]*)\] ((?:(?!^\[)[\s\S])*)/gm
let m;
while ((m = r.exec(s)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === r.lastIndex) {
r.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
首先要注意的是,我将你所有的\[(.*?)\]
改为\[([^\]]*)\]
。这是因为在这种情况下\[([^\]]*)\]
实际上比懒惰量词更好([^\]]*
意味着匹配任何不是]
的东西)。
((?:(?!^\[)[\s\S])*)
将以下内容捕获到捕获组4中
(?:(?!^\[)[\s\S])*
匹配以下任意次数(这是一个tempered greedy token)
(?!^\[)
负向前瞻确保后面的内容不匹配
^
在线的开头断言位置
\[
字面上匹配左方括号[
[\s\S]
匹配任何字符(包括换行符)它应该是本RegExp的第1组:\[(.*?)\] \[(.*?)\] \[(.*?)\]/gm
见:https://regex101.com/r/tC6mDp/1
你只需要匹配括号: