Link to home
Start Free TrialLog in
Avatar of MJ
MJFlag for United States of America

asked on

JavaScript Regex for 0-9/A-Z pattern match with Hyphen

I'm looking for a  Javascript regx that will detect a-z (case insensitive)  or 09 as a group and then a hyphen followed by any group  of a-z or 09  etc. Always will start/end with (a-z or 09) For example:

a12dd3-23-fff-11n3N33n3-988
9fkr-rtt488-344-45
r5999999Rrp-4-yei388dfi3-3444-fjj577-23
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
1234-567-8-922-222222-2-1111
Avatar of zc2
zc2
Flag of United States of America image

I would try
([a-zA-Z0-9]+-?)+

Open in new window

https://regexr.com/3vf1b
Avatar of MJ

ASKER

Hi zc2,
That doesn't seem to work,  as it allows anything I've tested, good or bad?
Could you post an input string which should not match?
Avatar of MJ

ASKER

Hi Zc2,
Try these two:

*********8
s@#$%^^
ASKER CERTIFIED SOLUTION
Avatar of zc2
zc2
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of MJ

ASKER

HI,
I tested again and it still works for strings ending with a hyphen but it shouldn't. Examples that should fail:

xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx-xxxx-
123-sx2M-34-
How about this:
^([a-zA-Z0-9]+-)+[a-zA-Z0-9]+$

Open in new window


https://regex101.com/r/GVxhMn/3
Avatar of MJ

ASKER

Hi Shaun,
I believe it still allows strings ending with a hyphen which I do not want.

Thanks!
Avatar of MJ

ASKER

This works:  ^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$
Avatar of MJ

ASKER

Thanks!