Reputation: 115
Trying to write a simple regex to match either of the following formats: XX-XXXXXX-XX-XX-XX
or XX-XXXXXX-XX-XX-XX-XX
where X
is a number (0-9)
or an alpha character (case insensitive).
I have tested the following expression:
/[0-9A-Za-z]{2}-[0-9A-Za-z]{6}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}(?:-[0-9A-Za-z]{2})/
where the final -XX
is a non capturing group.
I am trying to test against the following entries:
0F-F5G67E-H4-j6-j7
0F-F5G67E-H4-j6-j7-8J
But, it only matches the second one.
Heres the link for testing: http://regexr.com/3eebe
I will appreciate if any pro regexers can lend a hand.
Thanks
Upvotes: 0
Views: 133
Reputation: 16
Mark the group as optional by adding a ?
at the end:
/[0-9A-Za-z]{2}-[0-9A-Za-z]{6}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}(?:-[0-9A-Za-z]{2})?/
Upvotes: 0
Reputation: 13
You forgot to add ? (meaning "zero or one time") after your group /[0-9A-Za-z]{2}-[0-9A-Za-z]{6}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}(?:-[0-9A-Za-z]{2})?/
Also, add g
flag to match both groups in your testing environment.
And finally, why not just combine last three groups together: /[\w]{2}-[\w]{6}(?:-[\w]{2}){3,4}/g
?
Upvotes: 1
Reputation: 38502
You are missing a ?
following the non-capturing group so add a ?
and set the g
flag
[0-9A-Za-z]{2}-[0-9A-Za-z]{6}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}-[0-9A-Za-z]{2}(?:-[0-9A-Za-z]{2})?
Upvotes: 0
Reputation: 29431
Next time you can use quantifier {3,4}
:
[0-9A-Za-z]{2}-[0-9A-Za-z]{6}(?:-[0-9A-Za-z]{2}){3,4}
View it Online
Upvotes: 0