繁体   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