【问题标题】:regex multi line checkstyle module not working正则表达式多行检查样式模块不起作用
【发布时间】:2019-02-22 22:56:04
【问题描述】:

我正在尝试创建一个 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 中测试过

【问题讨论】:

  • 尝试在正则表达式value="(?m)Company[\s\n\r\R]*\.[\s\n\r\R]*INSTANCE[\s\n\r\R]*\.[\s\n\r\R]*getProduct"中开启多行标志

标签: java regex eclipse checkstyle maven-checkstyle-plugin


【解决方案1】:

我在这里做错了什么?

由于您使用的是 Java,因此每个换行符匹配器 \R 实例中的斜线都需要一个转义字符(其中 R 为大写)。

所以尝试改用这个正则表达式:

Company[\s\n\r\\R]*\.[\s\n\r\\R]*INSTANCE[\s\n\r\\R]*\.[\s\n\r\\R]*getProduct

我的正则表达式在 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 测试正则表达式,例如 freeformatterregexplanet

如果您在支持 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 “\”?有关为什么需要这样做的一些很好的解释。

【讨论】:

    【解决方案2】:

    我发现 RegexpMultiline 很难使用,因为它经常遇到像你这样的问题。相反,使用Regexp 检查,它允许更简单的正则表达式,并且可以忽略注释掉的代码:

    <module name="Regexp">
        <property name="format" value="\bCompany\s*\.\s*INSTANCE\s*\.\s*getProduct\b"/>
        <property name="illegalPattern" value="true"/>
        <property name="ignoreComments" value="true"/>
        <message key="illegal.regexp" value="Do not use Company Instance."/>
    </module>
    

    注意\b 标记以防止它匹配FooCompany 等。另请注意,此检查位于 TreeWalker 模块下。

    【讨论】:

      猜你喜欢
      • 2015-06-19
      • 1970-01-01
      • 2013-02-27
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 2023-04-02
      相关资源
      最近更新 更多