![](/img/trans.png)
[英]Javascript Regex - matching opening and closing parenthesis when nested
[英]Regex for matching string in parentheses including when opening or closing parenthesis is missing
我想匹配括號中的字符串(包括括號本身),並在缺少右括號或左括號時匹配字符串。
從環顧四周,我的理想解決方案將涉及條件正則表達式,但是我需要在 javascript 正則表達式引擎的限制范圍內工作。
我目前幾乎可以使用的解決方案: /\(?[^()]+\)|\([^()]+/g
。我可以將其拆分(可能更好的可讀性)但很想知道是否有是一種實現它的方法,而不會因為多個|
過於冗長。
可能有助於理解我通過示例嘗試實現的目標( highlighted
的部分是我想要匹配的部分):
(paren without closing
(paren in start)
字符串(in middle)
(at end of string)
paren without opening)
(string with only paren)
(with multiple)
括號(in a row)
這是我在regexr.com中設置的測試的鏈接。
您可以匹配以下正則表達式。
^\([^()]*$|^[^()]*\)$|\([^()]*\)
Javascript 的正則表達式引擎執行以下操作。
^ # match the beginning of the string
\( # match '('
[^()]*. # match zero or more chars other than parentheses,
# as many as possible
$ # match the end of the string
| # or
^ # match the beginning of the string
[^()]*. # match zero or more chars other than parentheses,
# as many as possible
\) # match ')'
$ # match the end of the string
| # or
\( # match '('
[^()]*. # match zero or more chars other than parentheses,
# as many as possible
\) # match ')'
我認為你做得很好。 問題是您需要在兩個地方匹配 [()] 並且其中只有一個需要為真,但兩者都不能為假,並且正則表達式並不那么聰明,無法保持 state 那樣。 因此,您需要檢查是否有 0 或 1 個打開或 0 或 1 個關閉在您擁有的替代方案中。
更新:
我的立場是正確的,因為你似乎關心的是有一個左括號或右括號你可以做這樣的事情:
.*[\(?\)]+.*
在英語中:任意數量的字符,帶有 ( 或 ) 后跟任意數量的字符。 不過,這會以任何順序匹配它們,所以如果你需要 ( 在關閉之前即使你似乎並不關心兩者是否都存在,這將不起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.