Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression for hyphen seperated strings

Tags:

regex

I created a regular expression for the format XX-XX-XX-XX-XX, where XX is a alphanumeric.

Regular expression is ^[a-z0-9A-Z]{2}-[a-z0-9A-Z]{2}-[a-z0-9A-Z]{2}-[a-z0-9A-Z]{2}$. But what I really want to do is to match the below patterns. My string should have one hyphen (-) for each 2 characters.

exapmle 1 : XX-            OK
exapmle 2 : XX-X           OK 
exapmle 3 : XX-XX-         OK 
exapmle 4 : XX-XX-XX       OK
exapmle 5 : XX-XX-XX-X     OK
exapmle 6 : XX-XX-X        OK
exapmle 7 : XX-XX--        NOT OK
exapmle 8 : XX-XX-X-       NOT OK
like image 461
ksr Avatar asked Feb 25 '23 10:02

ksr


1 Answers

This will do the trick. You basically want any number (zero or more) of XX- followed by zero, one or two X:

^([0-9A-Za-z]{2}-)*[0-9A-Za-z]{0,2}$
like image 105
paxdiablo Avatar answered Mar 02 '23 23:03

paxdiablo