What is the regular expression to remove whitespace inside brackets?

后端 未结 2 2024
庸人自扰
庸人自扰 2020-12-06 21:06

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

insert    
into  
abc      values   (    e   
, b    );

...what re

相关标签:
2条回答
  • 2020-12-06 21:44

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

    yourString.replaceAll("\n", " ").replaceAll("( ","(").replaceAll(" )",")").replaceAll(", ",",").replaceAll(" ,",",");
    
    0 讨论(0)
  • 2020-12-06 22:03

    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
    
    0 讨论(0)
提交回复
热议问题