匹配括号中有或没有文本 - 正则表达式

Match the parentheses with or without a text in it - Regex

以下是我的正文-

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 ( ).

我正在尝试匹配其中的文本 -

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

我还尝试了 \(*\),它匹配 ()( ))(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)
)

My Regular Expression - \(.\) which is not working.

匹配一对圆括号和恰好一个之间的其他字符。

I also tried \(*\) which is matching (), ) of ( ) and ) of (The Extremes of Good and Evil). Let me know what I am doing wrong here.

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

你想要这个:

\([^)]*\)

即:

  • 一个左括号,然后是
  • 除右括号外的零个或多个字符,后跟
  • 右括号。

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

这应该完全符合您的要求。在为每一行在非全局级别上使用它进行解析时 - 它将解析掉括号。

(?:\()  #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