donguy76
donguy76

Reputation: 640

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?

Upvotes: 3

Views: 8196

Answers (3)

Jonas Bjork
Jonas Bjork

Reputation: 168

It's easier to reverse it:

String regEx = "^[^a-zA-Z0-9\\*\\-\\_]+\$" /* This matches everything _but_ alnum and *-_ */

Upvotes: 0

cfrick
cfrick

Reputation: 37033

In Groovy the $ char in a string is used to handle replacements (e.g. Hello ${name}). As these so called GStrings are only handled, if the string is written surrounding it with "-chars you have to do extra escaping.

Groovy also allows to write your strings without that feature by surrounding them with ' (single quote). Yet the easiest way to get a regexp is the syntax with /.

assert "SDD884MMKG_JJGH1222" ==~ /^[a-zA-Z0-9*-_]+$/

See Regular Expressions for further "shortcuts".

The other points from @anubhava remain valid!

Upvotes: 4

anubhava
anubhava

Reputation: 785276

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.

Upvotes: 6

Related Questions