Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the regular expression to remove whitespace inside brackets?

Tags:

java

regex

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.

like image 587
Arslan Anwar Avatar asked Dec 13 '22 08:12

Arslan Anwar


1 Answers

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
like image 159
Tim Pietzcker Avatar answered Dec 14 '22 22:12

Tim Pietzcker