5

I am writing a program in Java to accept queries. If I have a query like

insert    
into  
abc      values   (    e   
, b    );

...what regular expression can I use to convert that into:

insert into abc values(e,b);

...or:

insert:into:abc:values(e,b);

Actually I want to know how I can I write a regular expression to remove whitespace within brackets only.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Arslan Anwar
  • 18,746
  • 19
  • 76
  • 105
  • May the brackets nest? If so, you're screwed (a Perl wizard may manage it, but the result won't be nice or maintainable and I wouldn't bet on it being portable to less sophisticated regex engines). –  Oct 11 '11 at 19:09
  • Lets keep it simple. That there are no nested brackets. – Arslan Anwar Oct 11 '11 at 19:10
  • This isn't exactly a solution to your problem, since you've already got some pretty great responses up above, but, if you're ever at a stand-still for something like this, I find that there are some great testers online -- I use [this one](http://regexpal.com) the most, since it's real-time, and has a nice reference sheet on the right side. – j6m8 Oct 11 '11 at 20:38

2 Answers2

14

Assuming correctly balanced parentheses, and no nested parentheses, the following will remove all whitespace within parentheses (and only there):

String resultString = subjectString.replaceAll("\\s+(?=[^()]*\\))", "");

It transforms

insert    
into  
abc      values   (    e   
, b    );

into

insert    
into  
abc      values   (e,b);

Explanation:

\s+      # Match whitespace
(?=      # only if followed by...
 [^()]*  # any number of characters except parentheses
 \)      # and a closing parenthesis
)        # End of lookahead assertion
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
0

As far as I see you don't need RegEx for this. That should work:

yourString.replaceAll("\n", " ").replaceAll("( ","(").replaceAll(" )",")").replaceAll(", ",",").replaceAll(" ,",",");
styrr
  • 829
  • 4
  • 9