Richie
Richie

Reputation: 5199

Regular expression in Groovy not returning expected results

I've been working on a regular expression with the following requirements.

    // Must be exactly 17 characters
    // Must only contain letters and numbers
    // Cannot contain the letters ‘I’, ‘O’ or ‘Q’
    // Must contain at least 1 alpha and 1 numeric character.

Thanks to some help on in another topic I managed to get a regular expression of

/^(?=.*[0-9])(?=.*[a-zA-Z])([a-hj-npr-z0-9]{17})$/

I was able to validate this as per https://regex101.com/r/cVz4b9/4/.

For some reason when I try this in Groovy though I don't get the same results.

def regex = /^(?=.*[0-9])(?=.*[a-zA-Z])([a-hj-npr-z0-9]{17})$/
println​ ('B1cCdDeEfFgGhHwww' ==~ regex)​​​ 

For example the below Groovy script prints false when I'm expecting true. Perhaps I'm not escaping something I should be? I am using the slashy string so I'm not sure why this would not work?

If anyone can pick out what's wrong that would help me a lot.

thanks

Upvotes: 1

Views: 565

Answers (2)

Valdi_Bo
Valdi_Bo

Reputation: 30971

Since \w matches [a-zA-Z_0-9], you can take the following ordered (and concise) approach:

  • Start with case insensitivity flag: (?i) . Since not revoked, it "works" till the end of the regex.
  • Put both positive lookaheads concerning a single digit and letter placed anywhere: (?=.*[\d])(?=.*[a-z]).
  • Put negative lookahead concerning 3 "forbidden" chars, but you must forbid also "_", matched by \w (see below): (?!.*[ioq_]).
  • Put the main clause concerning 17 word chars: [\w]{17} (instead of mentioning letters and digits separately, remember that "_" was forbidden earlier).

^ and $ are not needed, since ==~ checks whether the entire text is matched by the regex.

To sum up the regex can be: (?i)(?=.*[\d])(?=.*[a-z])(?!.*[ioq_])[\w]{17}.

Upvotes: 2

Mike W
Mike W

Reputation: 3932

It seems that case doesn't matter by your example so you could just add the case insensitivity flag (?i)

def regex = /^(?=.*[0-9])(?=.*[a-zA-Z])((?i)[a-hj-npr-z0-9]{17})$/

Upvotes: 1

Related Questions