![](/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.