Never was good at these things. We are using Checkstyle (for Java) to enforce good coding practices. One new check we would like to add is to identify when a certain API is used (potentially) incorrectly through the use of a regex check.
Incorrect usage examples:
BigDecimal.valueOf(someDouble).setScale(3);
someBigDecimalObject.setScale(6);
Correct usage examples:
BigDecimal.valueOf(someDouble).setScale(3, RoundingMode.HALF_UP);
someBigDecimalObject.setScale(1, RoundingMode.HALF_DOWN);
So,the regular expression I’m looking for is when “.setScale(” appears in the code that “RoundingMode.” appears somewhere after it. Or to add more clarity, the regular expression should be true when “.setScale(” appears but “RoundingMode.” doesn’t.
Thanks in advance
Off the top of my head:
What you want is to see
.setScale(...)where...doesn’t containRoundingMode. To explain further (assuming the Regex is being processed by Java):(?x:– introduce “whitespace” mode so that you can pad the regex with spaces for readability\.setScale \s* \(– look for.setScalewith arbitrary spaces then(Now the fun really begins: At every position until we encounter the trailing
)check whether the wordRoundingModeappears:(?:– start a group containing…(?! \bRoundingMode\b )– …a negative look-ahead assertion for the word RoundingMode, that is, the regex will fail to match if “RoundingMode” is detected; and then[^)]– match a non)character) *– repeat the above as often as required until\)– the closing “)” is detected.)– Finally, close the(?x:construct.Of course, this won’t work if there are nested
(...)expressions in the method call but you can’t solve that with a Java Pattern, you’ll need a dodgy Perl regex instead