开发者

Regular expression wrong matches

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?


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).


^[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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜