문제

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

도움이 되었습니까?

해결책 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)"

다른 팁

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

\((?!.*\().*?\)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top