复杂的正则表达式

Complex regular expression

本文关键字:正则表达式 复杂      更新时间:2023-09-26

我正在尝试找到一个正则表达式,它将执行以下操作(在Javascript中工作)。我想取一个字符串,其中包含一些标记,例如括号内的(token)。我的目标是捕获令牌(包括括号)。我将假设括号不是嵌套的,并且每个左括号最终都是封闭的。

我会使用的正则表达式是

[[^'(')]*|('(.*?'))]*

让我分解一下:

[            # Either of two things:
  [^'(')]*   # the first is a substring not containing parentheses
|
  (          # the second is to be captured...
    '(.*?')  # and should contain anything in parentheses - lazy match
  )
]*           # Any number of these blocks can appear

不用说,这是行不通的(否则我为什么要在这里问?

var a = /[[^'(')]*|('(.*?'))]*/;
a.exec('foo(bar)');

它在Firefox和Node中都失败了。我之前的尝试是一个稍微比较复杂的正则表达式:

(?:[^'(')]*('(.*?')))*[^'(')]*

可以描述如下

(?:              # A non-capturing group...
  [^'(')]*       # ...containing any number of non-parentheses chars
  ('(.*?'))      # ...followed by a captured token inside parentheses.
)*               # There can be any number of such groups
[^'(')]*         # Finally, any number of non-parentheses, as above

这将适用于foo(bar),但在foo(bar)(quux)上会失败,只对 quux 起作用。

我应该如何修复上述正则表达式?

则表达式中不能有任意数量的捕获组。 请改用/g 标志完成此操作: s.match(/'([^')]+')/g)

这工作找到 - 在 Chrome 中测试

<your string here>.match(/('(.*?'))/g)

它返回一个匹配数组:

str = 'Content(cap)(cap2)(cap3)'
str.match(/('(.*?'))/g)
-> ["(cap)", "(cap2)", "(cap3)"]

如果您的目标是捕获括号内的标记(包括分隔符),那么一个简单的正则表达式如下:

'([^)]*?')

会工作。

var a= /'([^)]+')/g;