Skip to content
Advertisement

Regex for no white space at the beginning and at the and and only one in between

I am creating a user input form where a user can enter his name and I want to use a regex for the following pattern:

^[A-Za-z_äÄöÖüÜß_.-]*

It only should accept the above letters, and dots if any and slashes if any.

Moreover I want it to accept white spaces but not at the beginning and not at the end and only one white space between name parts.

E.g. if user’s name is Dora F. T. Kov it should be valid.

If I am adding \s to my regex, it allows any amount of white spaces in my string anywhere.

How could I rewrite it based on the above concept?

Thank you a lot in advance!

Advertisement

Answer

How about:

^[A-Za-z_äÄöÖüÜß_.-]+(?: [A-Za-z_äÄöÖüÜß_.-]+)*$

See regex demo

  1. ^ – Matches start of string
  2. [A-Za-z_äÄöÖüÜß_.-]+ Matches one or more of these allowed characters
  3. (?: [A-Za-z_äÄöÖüÜß_.-]+)* – Followed by 0 or more occurrences of: single space followed by one or more of your allowed characters.
  4. $ – Matches end of string
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement