tags:

views:

57

answers:

2

I have been using the following regular expression in ASP.NET and Javascript:

[a-zA-ZöäüÖÄÜß0-9]{1}[a-zA-ZöäüÖÄÜß0-9_.\-]{2,14}[a-zA-ZöäüÖÄÜß0-9.!]{1}

Now, I am migrating to ASP.NET MVC and I am checking my code. I find that

'test'
%test

Are also matches. That's probably because not the whole string needs to be matched. And the test within 'test' is a valid match.

How do I need to change the RegEx to match the complete string and not only parts of it?

+1  A: 
^[a-zA-ZöäüÖÄÜß0-9]{1}[a-zA-ZöäüÖÄÜß0-9_.\-]{2,14}[a-zA-ZöäüÖÄÜß0-9.!]{1}$

where ^ matches the beginning and $ the end of line (text).

Péter Török
+3  A: 

If you're trying to match a whole string, use ^ and $ anchors:

^[a-zA-ZöäüÖÄÜß0-9][a-zA-ZöäüÖÄÜß0-9_.\-]{2,14}[a-zA-ZöäüÖÄÜß0-9.!]$

Note: I've also dropped {1} since it's completely redundant as a quantifier, by default any character or character class matches only single occurrence. You might also want to shorten your character classes using the case-insensitive modifier. (/i in Javascript).

SilentGhost
Thanks, it works great.
Sparhawk
What is it with all these pointless `{1}` s that have been popping up recently?!? I've think I've seen more in just this past week than in however many years I've used regex for. :S
Peter Boughton