I m programming a web application with asp.net mvc and c#. In a form a user should enter a name, a streetname and a city in different fields.
This is correct:
A b c
Abcd ef
Abcdef
This is not correct:
1abc
A1 bc
1 2 3
a b c (space at the start)
Question:
What is the correct regex for this?
How can i set the length?
In a second case I want to allow numbers 0123456789 too (like the chars)
This is what I have: '^[a-zA-Z][a-zA-Z ][a-zA-Z]$'
Thank you
You want to validate strings that only contain letter words separated with a single space between them.
You may use a regex like
^\p{L}+(?: \p{L}+)*$
Or, if any whitepsace is allowed:
^\p{L}+(?:\s\p{L}+)*$
See the regex demo
To make it only match strings of 3 or more chars, use
^(?=.{3})\p{L}+(?:\s\p{L}+)*$
^^^^^^^^
Details
^
- start of a string(?=.{3})
= a positive lookahead that requires any 3 chars immediately after the start of a string\p{L}+
- 1 or more any Unicode letters(?:\s\p{L}+)*
- zero or more repetitions of
\s
- any whitespace\p{L}+
- 1 or more any Unicode letters$
- end of stringNote that if you need to use it in ASP.NET, only use this regex to validate on the server side, as on the client side, this pattern might not be correctly handled by JavaScript regex.
You can use this regex:
^(?:\p{L}+ )*\p{L}+$
\p{L}
matches all unicode code points that are in the "Letters" category.
The regex matches 0 or more of \p{L}+
(one or more letters plus a space) and then ensures there is at least one or more letters.
Example code:
Console.WriteLine(Regex.IsMatch("abc def", @"^(?:\p{L}+ )*\p{L}+$"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With