簡體   English   中英

用於匹配括號中字符串的正則表達式,包括缺少左括號或右括號時

[英]Regex for matching string in parentheses including when opening or closing parenthesis is missing

我想匹配括號中的字符串(包括括號本身),並在缺少右括號或左括號時匹配字符串。

從環顧四周,我的理想解決方案將涉及條件正則表達式,但是我需要在 javascript 正則表達式引擎的限制范圍內工作。

我目前幾乎可以使用的解決方案: /\(?[^()]+\)|\([^()]+/g 。我可以將其拆分(可能更好的可讀性)但很想知道是否有是一種實現它的方法,而不會因為多個|過於冗長。

例子

可能有助於理解我通過示例嘗試實現的目標( highlighted的部分是我想要匹配的部分):

  1. (paren without closing
  2. (paren in start)字符串
  3. 字符串的括號(in middle)
  4. paren (at end of string)
  5. paren without opening)
  6. 沒有任何括號的字符串
  7. (string with only paren)
  8. 字符串(with multiple)括號(in a row)

這是我在regexr.com中設置的測試的鏈接。

您可以匹配以下正則表達式。

^\([^()]*$|^[^()]*\)$|\([^()]*\)

Javascript 演示

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 ')'

截至問題日期(2020 年 5 月 14 日), Regexr 的測試機制未按預期工作(匹配(with multiple)但不匹配( (in a row) )似乎是測試機制中的一個錯誤。 如果您在 Regexr 的“文本”模式下復制並粘貼這 8 個項目並測試您的表達式,您會看到它匹配(in a row) 。該表達式在Regex101中也可以正常工作。

我認為你做得很好。 問題是您需要在兩個地方匹配 [()] 並且其中只有一個需要為真,但兩者都不能為假,並且正則表達式並不那么聰明,無法保持 state 那樣。 因此,您需要檢查是否有 0 或 1 個打開或 0 或 1 個關閉在您擁有的替代方案中。

更新:

我的立場是正確的,因為你似乎關心的是有一個左括號或右括號你可以做這樣的事情:

 .*[\(?\)]+.*

在英語中:任意數量的字符,帶有 ( 或 ) 后跟任意數量的字符。 不過,這會以任何順序匹配它們,所以如果你需要 ( 在關閉之前即使你似乎並不關心兩者是否都存在,這將不起作用。

暫無
暫無

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

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