Click here to Skip to main content
15,891,905 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello ,

I am coverting a java application into c#, I have the following regular expression check:

C#
Regex regex = new Regex("[a-zA-Z0-9_\\.-]{1,20}");
            if (!regex.IsMatch(name))
            {
                return true;
            }



Why does the string "#####llll" pass the pattern matching?
I need a pattern with following criteria

string length 1-20
contains any apha numeric character, special characters like underscore,dot,hyphen
please help...
Posted
Updated 5-Apr-10 0:13am
v2

It passes because the "llll" part of the string fullfils the criteria - the "#####" part is ignored. Try it - Add
MessageBox.Show("Matched: " + regex.Match(name));
and you will see what I mean.

You could try:
Regex regex = new Regex("^[a-zA-Z0-9_\\.-]{1,20}");
            if (!regex.IsMatch(name))
            {
                return true;
            }
which forces the match to be at the beginning of the string.

It may be worth your while to get a copy of Expresso - it examines and generates Regular expressions - and its free!
 
Share this answer
 
The regular expression should be some thing like this ^[a-zA-Z0-9_\\.-]{1,20}$ Otherwise it will find the part of the string which is matching.
 
Share this answer
 
I see nothing obvious - what error are you getting? Is there a message? Exception?
 
Share this answer
 
Comments
Toli Cuturicu 8-Sep-10 12:09pm    
Reason for my vote of 2
See the other answers.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900