Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REGEX min. 4 chars, max 11, allow space and special chars

Tags:

regex

I have a regex on a RegularExpressionValidator .NET control: ^\w{4,11}$ Works fine. It allows the string length between 4 and 11. I would like it to allow space and special characters like "æ" "ø" "å" (danish characters).

Any suggestions?

like image 991
Kasper Skov Avatar asked Dec 05 '11 13:12

Kasper Skov


People also ask

How do I allow special characters in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .

Are spaces allowed in regex?

Yes, also your regex will match if there are just spaces.

How do you indicate a space in regex?

The most common forms of whitespace you will use with regular expressions are the space (␣), the tab (\t), the new line (\n) and the carriage return (\r) (useful in Windows environments), and these special characters match each of their respective whitespaces.

What does ?= Mean in regular expression?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).


2 Answers

How about ^.{4,11}$? Or just check that the line lenght is between 4 and 11. If this is not suitable, I think it is easier to match the characters you don't allow...

like image 104
Kimvais Avatar answered Sep 30 '22 11:09

Kimvais


Since you are talking about .net \w should include all unicode code points with the property letter. That means all letters from all languages in Unicode are already available in \w

So you just need to add the space and you are done:

^[\w ]{4,11}$

is matching "Foo æ ø å" in my test.

The '[\w ]' is a character class that includes now all characters included in \w and the space. If you need more characters, just add them inside the class.

\p{L} would be only the letters, you can use this if you don't want to allow digits.

like image 38
stema Avatar answered Sep 30 '22 09:09

stema