简体   繁体   中英

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?

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

If your strings may contain spaces around parentheses then you should consider parsing the Java rather than doing this with regex. This project has a Java parser which looks usable:

https://github.com/javaparser/javaparser

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM