Search code examples
regexgrailsgroovy

Groovy : RegEx for matching Alphanumeric and underscore and dashes


I am working on Grails 1.3.6 application. I need to use Regular Expressions to find matching strings.

It needs to find whether a string has anything other than Alphanumeric characters or "-" or "_" or "*"

An example string looks like:

SDD884MMKG_JJGH1222

What i came up with so far is,

String regEx = "^[a-zA-Z0-9*-_]+\$"

The problem with above is it doesn't search for special characters at the end or beginning of the string.

I had to add a "\" before the "$", or else it will give an compilation error.

- Groovy:illegal string body character after dollar sign;

Can anyone suggest a better RegEx to use in Groovy/Grails?


Solution

  • Problem is unescaped hyphen in the middle of the character class. Fix it by using:

    String regEx = "^[a-zA-Z0-9*_-]+\$";
    

    Or even shorter:

    String regEx = "^[\\w*-]+\$";
    

    By placing an unescaped - in the middle of character class your regex is making it behave like a range between * (ASCII 42) and _ (ASCII 95), matching everything in this range.