0

Following is the string I am using

(((Thermal) WN RR) AND ((Energy) SS AB)), Text only

Above text need to be converted to

Thermal AND Energy

How to achieve this. This should be generic like this should also work if the value is

((Thermal) WN TR)
((Thermal) WN RR) AND ((Energy) SS AB) OR ((Thermal) WN RR)

Any help would be greatly appreciated. Thanks in advance

Solution: Thank to @spOOm Using his regex, following is the code I used to solve the issue

q = <Query String>
q =     q.substring(0, q.lastIndexOf(')')+1);
q =     q.replace(/\(\(([^()]+)\)(?: [^()]+)+\)/g, "$1");

The first setup could be done by Regex but I am not a pro at regex. Thank you all..

Dilip Rajkumar
  • 7,006
  • 6
  • 60
  • 76

4 Answers4

2

Replacing \(\(([^()]+)\)(?: [A-Z]+)+\) by $1 may suit your needs:

Regular expression visualization

Visualization by Debuggex


In JavaScript:

var output = input.replace(/\(\(([^()]+)\)(?: [A-Z]+)+\)/g, "$1");
sp00m
  • 47,968
  • 31
  • 142
  • 252
1

I'm not sure if I understood your question correctly but if you want to get the innermost values in nested braces you can use this:

/\(((?:(?>[^\(]))*?)\)/g

It will capture all characters between "(" and ")" with the condition that there are no other "(" characters in between

In your last example it would capture

Thermal Thermal Thermal Energy Thermal

Demo

EDIT

If you need to match outside the nested braces too you can use this:

/\(((?:(?>[^\(]))*?)\)|\)((?:(?>[^\)]))*?)\(/g

I just added the same regex inverting the braces

In your last example it would match

Thermal , Thermal , Thermal AND Energy OR Thermal

Demo

Marco Lepore
  • 116
  • 1
  • 7
0

You can't do this with a regex, since I believe you are talking about arbitrarily nested braces. Reference

Community
  • 1
  • 1
Shadowen
  • 838
  • 5
  • 14
  • Or do you have a code to achieve this feature.. I am struggling for few hours..:) tnx in advance.. Using Javascript – Dilip Rajkumar Aug 13 '15 at 14:38
  • This problem might be harder than you expect. You're looking for some sort of recursive parser. Try using [this](http://stackoverflow.com/questions/524548/regular-expression-to-detect-semi-colon-terminated-c-for-while-loops/524624#524624) to extract brackets, and parse it recursively. – Shadowen Aug 13 '15 at 14:42
  • We're stepping into the territory of generating a [Parse Tree](http://infolab.stanford.edu/~ullman/ialc/spr10/slides/cfl2.pdf). – Shadowen Aug 13 '15 at 14:44
  • Please see the solution above. Thanks for all your help. – Dilip Rajkumar Aug 14 '15 at 07:09
0

I see you want the inner-most values, use this pattern

\(([^()]+)\)

Demo

\(              # "("
(               # Capturing Group (1)
  [^()]         # Character not in [()] Character Class
  +             # (one or more)(greedy)
)               # End of Capturing Group (1)
\)              # ")"
alpha bravo
  • 7,838
  • 1
  • 19
  • 23