匹配括号中带或不带文本的括号 - 正则表达式



以下是我的文字-

Lorem Ipsum来自"de Finibus"的第1.10.32和1.10.33节 Bonorum et Malorum"(善恶的极端),作者:西塞罗,作者: 公元前45年。这也应该匹配 () 和 ( )。

我试图在其中匹配文本 -

  • (善与恶的极端)
  • ()
  • ( )

我的正则表达式 -(.)不起作用。

我还尝试了(*)匹配())( )(The Extremes of Good and Evil))。让我知道我在这里做错了什么。

您需要一个量词*来匹配括号内的零个或多个字符。也使它懒惰?所以只要它到达第一个右括号(.*?)它就会停止:

var s = 'Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This should also match () and ( ).'
console.log(
s.match(/(.*?)/g)
)

我的正则表达式 - \(.\) 不起作用。

这将一对括号与中间正好有一个其他字符匹配。

我还尝试了\(*\),它与()的(),)和(善恶的极端)相匹配。让我知道我在这里做错了什么。

在那里,您匹配任何数字,包括零的左括号(因为通配符适用于左括号),后跟右括号。

你想要这个:

([^)]*)

那是:

  • 左括号,后跟
  • 右括号以外的零个或多个字符,后跟
  • 右括号。

您需要以某种方式从中间的字符中排除右括号,否则将从第一个左括号到最后一个右括号的所有内容作为单个匹配项进行匹配。

这应该与您正在寻找的内容完全匹配。当在非全局级别为每一行使用它进行解析时 - 它将解析括号。

(?:()  #Non-Capture Group Parenthesis - for advanced submatching regex.
(       # Start Capture Group 1
(?!)) # Negative Lookahead
.*?  # Match all characters except line break + Lazy
)?      # End Capture Group 1 + Lazy (empty parenthesis)
(?:))  #Non-Capture Group Parenthesis - for advanced submatching regex.

见下文...

var s = 'Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This should also match () and ( ).'
console.log(
s.match(/(?:()((?!)).*?)?(?:))/g)
)
//CONSOLE OUTPUT
(3) ["(The Extremes of Good and Evil)", "()", "( )"]
0: "(The Extremes of Good and Evil)"
1: "()"
2: "( )"
length: 3

最新更新