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 only allow dash in between characters

I have this regex ^[A-ZÆØÅa-zæøå\ \-]{2,50}$ for validating names. How can I make it allow only one "-". I want it to accept names like this:

Janet Smith-Johnson
Mary-Ann Johnson
Sara Mary John-Smith
Sara Johnson
Sara Mary Johnson

But it can’t allow names that starts with - and ends with -. Like:

-Janet Mary
Mary-

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

>Solution :

You can use

^(?=.{2,50}$)(?!(?:.*-){2})[A-ZÆØÅa-zæøå]+(?:[- ][A-ZÆØÅa-zæøå]+)*$

See the regex demo.

If you are using the regex in C# or with u flag in JavaScript that supports ECMAScript 2018+ standard, you can also match any Unicode letter with \p{L}:

^(?=.{2,50}$)(?!(?:.*-){2})\p{L}+(?:[- ]\p{L}+)*$

Details:

  • ^ – start of string
  • (?=.{2,50}$) – two to fifty chars in the string allowed
  • (?!(?:.*-){2}) (or (?!(?:[^-]*-){2}) in the real code is more efficient) – no two hyphens are allowed
  • [A-ZÆØÅa-zæøå]+ – one or more letters from the set (\p{L} matches any Unicode letter)
  • (?:[- ][A-ZÆØÅa-zæøå]+)* – zero or more sequences of either space or - and then one or more letters
  • $ – end of string.
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