Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

java - What is the regular expression to remove whitespace inside brackets?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...