我需要一些帮助才能编写一个正则表达式,该正则表达式将括号中的字符串与嵌套括号匹配,并以pattern开头。 (注意:'父'括号中的文字可能没有嵌套括号)
示例:
Some text (pattern: SOME TEXT THAT (I WANT TO EXTRACT)) a bit more text (another pattern: ignore that text) and may be a little more text
结果应为:SOME TEXT THAT (I WANT TO EXTRACT)
Some text (pattern: SOME TEXT THAT (I WANT TO EXTRACT)) a bit more text (another pattern: ignore that text) and may be a little more text
结果应为SOME TEXT THAT (I WANT TO EXTRACT)
Some text (pattern: SOME TEXT THAT I WANT TO EXTRACT) a bit more text (another pattern: ignore that text) and may be a little more text
结果应为SOME TEXT THAT I WANT TO EXTRACT
RegEx我试过/\((pattern:?\s?([^\)]+))\)/gi
错过了嵌套)
答案 0 :(得分:1)
要从示例数据中提取文本,我认为您可以使用此正则表达式:
\(pattern
:?
\s?
(
.+?
\)
\)
var string = "Some text (pattern: SOME TEXT THAT (I WANT TO EXTRACT)) a bit more text (another pattern: ignore that text) and may be a little more text Some text (pattern: SOME TEXT THAT I WANT TO EXTRACT) a bit more text (another pattern: ignore that text) and may be a little more text";
var myRegexp = /\(pattern:?\s?(.+?\)?)\)/g;
var matches;
while ((matches = myRegexp.exec(string)) !== null) {
console.log(matches[1]);
}

答案 1 :(得分:0)
因此,您正在寻找括号内的所有文本,以“pattern:”开头,后跟一个字符串,可选择包含一组匹配的括号。
这远非可读,但这样做:
\(pattern:([^()]+|[^(]+\([^)]*\)[^()]*)\)
在单词中:查找(pattern: ...)
其中...
是一串不是括号的字符(让我们称之为NPC - 即[^()]+
部分)或一系列NPC跟随通过一个左括号,然后是一系列NPC,接着是一个右括号和另外一个NPC字符串(即[^(]+\([^)]*\)[^()]*
部分)。
当然,这不会处理更多级别或嵌套,但如果我理解正确的问题,则不需要它(没有办法制定处理任意嵌套的正则表达式)。