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_äÄöÖüÜß_.-]+)*$
^
– Matches start of string[A-Za-z_äÄöÖüÜß_.-]+
Matches one or more of these allowed characters(?: [A-Za-z_äÄöÖüÜß_.-]+)*
– Followed by 0 or more occurrences of: single space followed by one or more of your allowed characters.$
– Matches end of string