[英]Regex to remove spaces around parenthesis in Java
What I would like to do is change things like printf ( ... );
我想做的是更改诸如printf ( ... );
to printf(...);
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? 我已经尝试过line = line.replaceAll("\\\\s([(])\\\\s", "(");
,但这不起作用。我应该使用什么表达式?
You may use 您可以使用
"\\s*\\(\\s*([^)]*?)\\s*\\)\\s*"
And replace with ($1)
. 并替换为($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. 问题的关键是,在两侧(
和)
可以匹配空格与\\s*
,但是为了前的空格匹配)
,则需要自使用延迟匹配[^)]
,任何字符相匹配,但一)
能也匹配空格。
Or, just match all whitespace around any ()
: 或者,只需匹配任何()
周围的所有空格:
"\\s*([()])\\s*"
And replace with $1
. 并替换为$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. 如果您的字符串的括号中可能包含空格,那么您应该考虑解析Java,而不是使用正则表达式进行解析。 This project has a Java parser which looks usable: 这个项目有一个看起来有用的Java解析器:
https://github.com/javaparser/javaparser https://github.com/javaparser/javaparser
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.