Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow only letters and "special" letters (éèà etc.) through a regex

Tags:

c#

regex

I am trying to match a string to see if it only consists out of letters. All kinds of letters should be allowed. So the typical a-zA-Z, but also áàéèó... etc.

I tried to match it with the following regex: ([\S])*

But this also allows characters like \/<>*()... etc. Those are obviously characters that don't belong in a name. How does the regex looks like when i only want to allow letters and 'special' letters?

like image 352
Vivendi Avatar asked Feb 28 '13 09:02

Vivendi


2 Answers

You can use the character class that says exactly that:

\p{L}

So the regex

^\p{L}+$

will match if the string consists only of letters. If you expect combining characters, then

^(\p{L}\p{M}*)+$

works.

Quick PowerShell test:

PS> 'foo','bär','a.b','&^#&%','123','кошка' -match '^\p{L}+$'
foo
bär
кошка
like image 25
Joey Avatar answered Sep 21 '22 02:09

Joey


For a non-REGEX solution you can use char.IsLetter

Char.IsLetter Method

Indicates whether the specified Unicode character is categorized as an alphabetic letter.

string str = "Abcáàéèó";
bool result = str.All(char.IsLetter);

This would give false result for digits and \/<>*() etc.

like image 87
Habib Avatar answered Sep 19 '22 02:09

Habib