I am trying to update the current regex ^[^-]*-?[^-]*$ to take AlphaNumeric only for the first & last character and accept having AlphaNumeric with only 0 or 1 hyphen in the middle in regex C#.
Please check below the valid and invalid values.
Invalid values:
-A
B2-
A--B
#12
Valid values:
A
A-B
"" // empty
1A
12
Please advise?
Thank you,
>Solution :
You can make the whole pattern optional, and only allow starting with chars A-Z 0-9 with an optional part for - and again chars A-Z 0-9:
^(?:[A-Z0-9]+(?:-[A-Z0-9]+)?)?$
If the match should be case insensitive, you can either use [a-zA-Z0-9] or start the pattern with (?i)
Explanation
^Start of string(?:Non capture group[A-Z0-9]+Match 1+ chars A-Z0-9(?:-[A-Z0-9]+)?Optionally match-and 1+ chars A-Z0-9
)?Close the non capture group and make the whole part optional$End of string
Or matching any kind of letter and any kind of number:
^(?:^[\p{L}\p{N}]+(?:-[\p{L}\p{N}]+)?)?$