I am trying to create a checkstyle rule where I want to prevent the use of "Company.INSTANCE.getProduct" from the below line.
private final Customer customerObj = Company.
INSTANCE.getProduct();
I added the below module in 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>
However, it does not work for multiline statements as in the above example. What am I doing wrong here? My regex works as tested in regex101.com
Since you are using Java you need an escape character for the slash in each instance of the linebreak matcher \R (where R is uppercase).
So try using this regular expression instead:
The regex101 web site does not support Java:
You must have been testing your regex with a different flavor such as PHP or JavaScript which masked the problem. However, there are plenty of other web sites that do support the testing of regular expressions with Java such as freeformatter and regexplanet.
If you run the regex you were providing to CheckStyle in a tester supporting Java you will get an Illegal/unsupported escape sequence error like this:
Prefixing an additional backslash to each instance of the linebreak matcher fixes this problem.
Rather than using a web site, you can also verify your regex yourself in a trivial Java program:
Note that in this case you need four backslashes before the R. See Why String.replaceAll() in java requires 4 slashes “\\” in regex to actually replace “\”? for some great explanations on why that is required.