Link to home
Start Free TrialLog in
Avatar of tonelm54
tonelm54

asked on

RegEx returning too many results

Im trying to write a jQuery validation method, but having issues getting the RegEx to match up.

Im trying to match a 16 character string, which has to be uppercase.
First 5 characters need to be A-Z
Next 6 characters are numeric
Next 2 charachers are A-Z
Last 3 characters can be A-Z or 0-9

So I got the following regex statment:-
5[A-Z]6[0-9]2[A-Z]3[[A-Z]|[0-9]

However when I run it thought an online checker it says it has matched 8, where surely it should say its matched 1, I can then put into my jQuery to say if the match == 1 then its good else there is a problem.

Any ideas what Im doing wrong, or am I miss understanding something here?
Avatar of kaufmed
kaufmed
Flag of United States of America image

That's not how quantifiers work in regex. You need curly braces around the quantity, and the quantity goes after the thing you want that many of.

Per your rules:

^[A-Z]{5}[0-9]{6}[A-Z]{2}[A-Z0-9]{3}$

Open in new window


The ^ and $ make sure the pattern matches the whole string, and not just part of it.

This is a great site for learning about regex:  https://www.regular-expressions.info/
Avatar of tonelm54
tonelm54

ASKER

sorry, still learning

I just tried that regex statement with
ABCDE123456AZ123

and it says 0 matches, but surely it should read 1 match as the string matches the criteria doesn't it?

Sorry if I'm being dumb here
You'd probably need to show your code. The pattern is working fine for me.

Match: https://regexr.com/4211m
No match: https://regexr.com/4211p
Maybe you don't need ^ and $ in the pattern

[A-Z]{5}[0-9]{6}[A-Z]{2}[A-Z0-9]{3}

Open in new window

@Subodh Tiwari

Well, as I mentioned, keeping those anchors in the pattern makes the entire string match the pattern. If the requirement was to simply find a string that matches that pattern from within a larger string, then leaving the anchors out makes sense. This question sounds more like validation, in which case the anchors (most likely) need to be there.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.