Search code examples
javaregexreplaceall

Regex to remove spaces around parenthesis in Java


What I would like to do is change things like printf ( ... ); to printf(...); with a regular expression. I've tried variations of line = line.replaceAll("\\s([(])\\s", "(");, but this isn't working. What expression should I be using?


Solution

  • You may use

    "\\s*\\(\\s*([^)]*?)\\s*\\)\\s*"
    

    And replace with ($1). See regex demo

    The point is that on both sides of ( and ) you can match whitespace with \s*, but in order to match the whitespace before the ), you need to use lazy matching since [^)] that matches any character but a ) can also match whitespace.

    Or, just match all whitespace around any ():

    "\\s*([()])\\s*"
    

    And replace with $1.

    See another demo