簡體   English   中英

復雜的正則表達式

[英]Complex regular expression

我試圖找到一個正則表達式,它將執行以下操作(在Javascript中工作)。 我想在括號中包含一些包含一些令牌(token)(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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM