son.a son.a - 18 days ago 6
Android Question

Reverse regexp in checkstyle

I’m trying to add a checkstyle, which will limit number of symbols in android string resource. I’m using RegexpSingleLine (also tried with Regexp), and already have a regexp expression. Now the problem is that it asserts when number of symbols in string is in range, but I need to assert in opposite case, when the number is outside of the range. So I need to reverse the expression somehow (or maybe use some property). Could someone help?
Here's my check.

<module name="RegexpSingleline">
<property name="fileExtensions" value="xml"/>
<property name="format" value='^\s*&lt;string\s*name="string_name"&gt;(.{5,10})&lt;'/>
</module>

Answer

I assume from your question that you want to flag Strings that are not 5-10 characters in length. With Checkstyle, you must find a regular expression which does that. There is no "invert" option for this check.

This should do it (explanation):

<module name="RegexpSingleline">
    <property name="fileExtensions" value="xml"/>
    <property name="format"
        value='^\s*&lt;string\s*name="string_name"&gt;(?![^&lt;]{5,10}&lt;)([^&lt;].*?)&lt;'/>
</module>

The above will not match empty strings. If you need to flag empty Strings as well, use this (explanation):

<module name="RegexpSingleline">
    <property name="fileExtensions" value="xml"/>
    <property name="format"
        value='^\s*&lt;string\s*name="string_name"&gt;(?:&lt;|(?![^&lt;]{5,10}&lt;)([^&lt;].*?)&lt;)'/>
</module>
Comments