Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex that accept AlphaNumeric as first & last character and accept having AlphaNumeric with only 0 or 1 hyphen in the middle

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

-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

Regex demo

Or matching any kind of letter and any kind of number:

^(?:^[\p{L}\p{N}]+(?:-[\p{L}\p{N}]+)?)?$

Regex demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading