Search code examples
javaregexhibernate-validatorspring-modules

Decode Regex expression - ^[a-zA-Z0-9 "'&!#$%()*+,-./:;?@[\\]^_`{|}~]+$


Using Java

I am not a regular on regex, I came across the following regex as part of migration of springmodules-validation stuff to latest.

^[a-zA-Z0-9 "'&!#$%()*+,-./:;?@[\\]^_`{|}~]+$

What exactly is this doing? I need to understand this to write unit test to this validation. By the way I'm using it in a Java project.

One more interesting thing, I tried this expression in hibernate-validator as follows:

@Pattern(regexp = "^[a-zA-Z0-9 "'&!#$%()*+,-./:;?@[\\]^_`{|}~]+$")

Then my intellijIDEA shows an error at the end of the line saying Unclosed character class. is the regex expression is properly formed?

Update

It seems the expression is malformed, I see the following exception while trying to test this:

java.util.regex.PatternSyntaxException: Unclosed character class near index 57
^[a-zA-Z0-9 "'&!#$%()*+,-./:;?@[\]^_`{|}~]+$

Here is the original expression from one of the xml files which I'm trying to migrate:

<regexp apply-if="creativeType == 'Text'" expression="^[a-zA-Z0-9 

&quot;&apos;&amp;!#$%()*+,-./:;?@[\\]^_`{|}~]+$"/>

Am I missing anything?

Working Solution

regexp = "^[a-zA-Z0-9 \"'&!#$%()*+,-./:;?@\\[\\]^_`{|}~]+$"

this way I have assigned it to a string and which works perfectly for me Thank you all!


Solution

  • The translated expression would look something like

    ^[a-zA-Z0-9 "'&!#$%()*+,-./:;?@\[\]^_`{|}~]+$
    

    and means a line of letter, digits and a set of other characters (like different brackets, where ] has to be escaped for not meaning the end of a character class).