Search code examples
javascriptregexcharacter-class

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


Following is my text -

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

In which I am trying to match the text -

  • (The Extremes of Good and Evil)
  • ()
  • ( )

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.


Solution

  • You need a quantifier * to match zero or more characters inside the parenthesis. Also makes it lazy ? so it stops as long as it reaches the first close parenthesis \(.*?\):

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