gpt4 book ai didi

java - 正则表达式多行 checkstyle 模块不工作

转载 作者:行者123 更新时间:2023-11-30 10:11:32 24 4
gpt4 key购买 nike

我正在尝试创建一个 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 的正则表达式,您将得到一个非法/不受支持的转义序列错误,如下所示:

patternException

为换行符匹配器的每个实例添加一个额外的反斜杠前缀可以解决这个问题。

除了使用网站,您还可以在简单的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com