什么是可以将括号中的文本与嵌套括号匹配的RegEx

时间:2017-11-24 23:00:34

标签: javascript regex

我需要一些帮助才能编写一个正则表达式,该正则表达式将括号中的字符串与嵌套括号匹配,并以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错过了嵌套)

2 个答案:

答案 0 :(得分:1)

要从示例数据中提取文本,我认为您可以使用此正则表达式:

\(pattern:?\s?(.+?\)?)\)

  • 匹配\(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字符串(即[^(]+\([^)]*\)[^()]*部分)。

当然,这不会处理更多级别或嵌套,但如果我理解正确的问题,则不需要它(没有办法制定处理任意嵌套的正则表达式)。