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

I have an issue in regular expression matching...
C#
string x = "user = 'sa' password='eX65dere' server = 'localhost'";
Regex rx = new Regex("password=\'([a-zA-Z0-9]\\_+)\'");
var r = rx.Match(x);
            if (r.Groups.Count > 0)
            {
                var g1 = r.Groups[0]; 
                label1.Text = g1.ToString();
            }


while executing this, I have got the following error message. parsing "password='([a-zA-Z0-9]\_+)'" - Unrecognized escape sequence \_. Can anyone help me on this?

Thanks
Sebastian
Posted
Updated 22-Mar-12 2:41am
v2

I have solved this by changing the expression as follows...
C#
Regex rx = new Regex(@"password='([a-zA-Z0-9\\%^&_*]+)\'");


--------------


again i have another question... Here is my updated expression...
C#
string x = "user = 'sa' password='e X65dere!@#$%^&*()' server = 'localhost'";
Regex rx = new Regex(@"password=\'([a-zA-Z0-9\\!@#$%^&*|() _'""*-+{}<>,.;/?:~`\[\]\\\\]+)\'");
    var r = rx.Match(x);
    if (r.Groups.Count > 0)
       {
          var g1 = r.Groups[0];
          MessageBox.Show(g1.ToString());
       }


In this case it will match for every small & large cap letters, numbers and special characters except = . If the password contains = the expression fails... can you please help?

Regards
Sebastian
 
Share this answer
 
v2
if you want \ to be part of regex then you will have to escape itself so instead of \ write \\ and you will be fine. [since \ is escape character.]

or do it like:

C#
Regex rx = new Regex(@"password='([a-zA-Z0-9]\_+)\'");
 
Share this answer
 
v2
Comments
Sebastian T Xavier 22-Mar-12 8:43am    
Regex rx = new Regex("password=\'([a-zA-Z0-9]+)\'"); will works fine... And it will match for all small caps , large caps & numbers. Now I have added \\_ to match the _ , then it throws this error....so How I can escape this?
Sebastian T Xavier 22-Mar-12 8:45am    
Like this what shall i do to match ' and " . How I can escape these two.
Rahul Rajat Singh 22-Mar-12 8:46am    
see the edited portion. use the @ to take strings literally and avoind using escape characters.
Sebastian T Xavier 22-Mar-12 8:48am    
That also have the same issue...
Rahul Rajat Singh 22-Mar-12 8:50am    
but why are you trying to ecsape _ use this

Regex rx = new Regex(@"password='([a-zA-Z0-9]_+)\'");
How we can match _ in a regular expression?
 
Share this answer
 

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