Reputation: 5199
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
Reputation: 30971
Since \w
matches [a-zA-Z_0-9]
, you can take the following ordered (and concise) approach:
(?i)
. Since not revoked,
it "works" till the end of the regex.(?=.*[\d])(?=.*[a-z])
.\w
(see below): (?!.*[ioq_])
.[\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
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