I am new to Regular Expression and can't seem to do the proper syntax for what I need to do. I need regular expression for an alphanumeric string that can be 1-8 characters long and can contain at most 1 dash, but can't be a single dash alone.
Valid:
A-
-A
1234-678
ABC76-
Invalid:
-
F-1-
ABCD1234-
---
Thanks in advance!
One way. (Sorry if this is already posted)
# ^(?=[a-zA-Z0-9-]{1,8}$)(?=[^-]*-?[^-]*$)(?!-$).*$
^ # BOL
(?= [a-zA-Z0-9-]{1,8} $ ) # 1 - 8 alpha-num or dash
(?= [^-]* -? [^-]* $ ) # at most 1 dash
(?! - $ ) # not just a dash
.* $
Edit: Just extend it for segments separated by comma's
# ^(?!,)(?:(?=(?:^|,)[a-zA-Z0-9-]{1,8}(?:$|,))(?=(?:^|,)[^-]*-?[^-]*(?:$|,))(?!(?:^|,)-(?:$|,)),?[^,]*)+(?<!,)$
^ # BOL
(?! , ) # does not start with comma
(?: # Grouping
(?=
(?: ^ | , )
[a-zA-Z0-9-]{1,8} # 1 - 8 alpha-num or dash
(?: $ | , )
)
(?=
(?: ^ | , )
[^-]* -? [^-]* # at most 1 dash
(?: $ | , )
)
(?!
(?: ^ | , )
- # not just a dash
(?: $ | , )
)
,? [^,]* # consume the segment
)+ # Grouping, do many times
(?<! , ) # does not end with comma
$ # EOL
Edit2: If your engine doesn't support lookbehinds, this is same thing but without
# ^(?!,)(?:(?=(?:^|,)[a-zA-Z0-9-]{1,8}(?:$|,))(?=(?:^|,)[^-]*-?[^-]*(?:$|,))(?!(?:^|,)-(?:$|,))(?!,$),?[^,]*)+$
^ # BOL
(?! , ) # does not start with comma
(?: # Grouping
(?=
(?: ^ | , )
[a-zA-Z0-9-]{1,8} # 1 - 8 alpha-num or dash
(?: $ | , )
)
(?=
(?: ^ | , )
[^-]* -? [^-]* # at most 1 dash
(?: $ | , )
)
(?!
(?: ^ | , )
- # not just a dash
(?: $ | , )
)
(?! , $ ) # does not end with comma
,? [^,]* # consume the segment
)+ # End Grouping, do many times
$ # EOL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With