我不确定您是否可以轻松编写 Checkstyle 扩展,因为Checkstyle SDK Gui的 AST 浏览代码在以下方面没有任何区别:
else if
和
else
if
在每种情况下,else
是一个LITERAL_ELSE
在其中if
...
所以通用正则表达式else[ \t]*[\r\n]+[ \t]*if
确实是检测这种代码的一种快速方法。
修复正则表达式以包括案例:
- 在换行符之前/之后没有空格而不是制表符
- 这是多个换行符。
当然,您不想使用\s
空格正则表达式,因为它本身包含换行符。将空格与返回字符分开会更清楚。
Note: in Checkstyle 5.0beta, do not use "Generic Illegal Regexp", but rather the "Regexp" module:
you can configure that RegExp module as 'illegalPattern' (with an associated Severity of 'Warning'), and you do not have to use any kind af 'multi-line' flag: the regexp is enough.
Regexp
Description
A check that makes sure that a specified pattern exists, exists less than a set number of times, or does not exist in the file.
This check combines all the functionality provided by RegexpHeader, GenericIllegalRegexp and RequiredRegexp, except supplying the regular expression from a file.
It differs from them in that it works in multiline mode. It's regular expression can span multiple lines and it checks this against the whole file at once. The others work in singleline mode. Their single or multiple regular expressions can only span one line. They check each of these against each line in the file in turn.
Thomas mentions in the comments:
The checkstyle AST does have line number information.
See "Is there any Checkstyle/PMD/Findbugs rule to force “<code>else if” to be on the same line?"
(in which one has to use a custom check, and not a regex match).