我正在尝试创建一个 checkstyle 规则,以防止使用下面一行中的“Company.INSTANCE.getProduct”。
private final Customer customerObj = Company.
INSTANCE.getProduct();
我在 checkstyle xml 中添加了以下模块。
<module name="RegexpMultiline">
<property name="format" value="Company[\s\n\r\R]*\.[\s\n\r\R]*INSTANCE[\s\n\r\R]*\.[\s\n\r\R]*getProduct"/>
<property name="message" value="Do not use Company Instance."/>
</module>
但是,它不适用于上面示例中的多行语句。我在这里做错了什么?我的正则表达式在 regex101.com 中进行了测试
最佳答案
What am I doing wrong here?
由于您使用的是 Java,因此您需要在换行匹配器 \R 的每个实例中为斜杠添加一个转义字符(其中 R 为大写)。
所以尝试使用这个正则表达式:
Company[\s\n\r\\R]*\.[\s\n\r\\R]*INSTANCE[\s\n\r\\R]*\.[\s\n\r\\R]*getProduct
My regex works as tested in regex101.com
regex101 网站 does not support Java :
The website does not support JAVA as a flavour. The Code generator only takes your regex and puts it into a code template. It does not validate the regex for you.
您一定是用不同的风格(例如 PHP 或 JavaScript)测试了您的正则表达式,从而掩盖了问题。然而,还有很多其他网站支持使用 Java 测试正则表达式,例如 freeformatter和 regexplanet 。
如果您在支持 Java 的测试器中运行向 CheckStyle 提供的正则表达式,您将收到如下所示的非法/不支持的转义序列错误:
在换行匹配器的每个实例前添加一个额外的反斜杠可以解决此问题。
您还可以在一个简单的 Java 程序中自行验证您的正则表达式,而不是使用网站:
String regex = "Company[\\s\\n\\r\\\\R]*\\.[\\s\\n\\r\\\\R]*INSTANCE[\\s\\n\\r\\\\R]*\\.[\\s\\n\\r\\\\R]*getProduct";
String text = "private final Customer customerObj = Company.\n"
+ "INSTANCE.getProduct();";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
System.out.println("find? " + matcher.find());
System.out.println("matches? " + matcher.matches());
请注意,在这种情况下,您需要在 R 之前添加四个反斜杠。请参阅Why String.replaceAll() in java requires 4 slashes “\\” in regex to actually replace “\” ?关于为什么需要这样做的一些很好的解释。
关于java - 正则表达式多行 checkstyle 模块不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52394462/