Question

I am new to regular expressions. I am trying to get the contents within the brackets using regex

Examples

  1. 7+(4*6) ---> (4*6)
  2. (44/(2*( 1 + 3))) ----> ( 1 + 3)
  3. (54-(23+12)) ----> (23+12)

So, my expected output starts with ( followed by digit followed by space(may be not) followed by any of the four operators (+,-,*,/) followed by space(may be not) followed by ).

Thanks in advance...

Was it helpful?

Solution 2

Try this:

\( *\d+ *[-+*/] *\d+ *\)

It means:

  • Match the character "(" literally.
  • Match the character " " literally.
    • Between 0 and unlimited times, as many as possible, giving back as needed (greedy).
  • Match a single digit 0..9
    • Between 1 and unlimited times, as many as possible, giving back as needed (greedy).
  • Match the character " " literally.
    • Between 0 and unlimited times, as many as possible, giving back as needed (greedy).
  • Match a single character present in the list "-+*/".
  • Match the character " " literally.
    • Between 0 and unlimited times, as many as possible, giving back as needed (greedy).
  • Match a single digit 0..9
    • Between 1 and unlimited times, as many as possible, giving back as needed (greedy).
  • Match the character " " literally.
    • Between 0 and unlimited times, as many as possible, giving back as needed (greedy).
  • Match the character ")" literally.

Examples:

var regExp = /\( *\d+ *[-+*/] *\d+ *\)/;
"7+(4*6)".match(regExp)[0];            // "(4*6)"
"(44/(2*( 1 + 3)))".match(regExp)[0];  // "( 1 + 3)"
"(54-(23+12))".match(regExp)[0];       // "(23+12)"

OTHER TIPS

You can use lookahead to grab inner most parentheses and enclosed text.

This regex should work:

\((?=[^(]*$)[^)]*\)

TESTING:

'7+(4*6)'.match(/\((?=[^(]*$)[^)]*\)/);
//=> ["(4*6)"]

'(44/(2*( 1 + 3)))'.match(/\((?=[^(]*$)[^)]*\)/);
//=> ["( 1 + 3)"]

'(54-(23+12))'.match(/\((?=[^(]*$)[^)]*\)/);
//=> ["(23+12)"]

Online Demo: http://regex101.com/r/fQ2iZ2

\.*(\([^()]*\))\.*

And your best pal.

try this variant

\((?!.*\().*?\)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top