Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse string with regex

Tags:

c#

regex

I am trying to search a string for email addresses, but my regex does not work, when the string contains other characters than the email. Meaning, if I try on a small string like "[email protected]", the regex finds a match. If I insert a blank space in the string, like: " [email protected]", the regex does not find an email match.

Here is my code(the regex pattern is from the web):

            string emailpattern = @"^(([^<>()[\]\\.,;:\s@\""]+"

                    + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"

                    + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"

                    + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"

                    + @"[a-zA-Z]{2,}))$";
            Regex rEmail = new Regex(emailpattern);
            string str = @" [email protected]";
            MatchCollection mcolResults = rEmail.Matches(str);
            MessageBox.Show(mcolResults.Count.ToString());

Please let me know what am I doing wrong.

Thank you.

Best regards,

like image 867
Amc_rtty Avatar asked Jul 01 '26 06:07

Amc_rtty


1 Answers

^ and $ mean (respectively) the start and end of the input text (or line in multi-line mode) - generally used to check that the entire text (or line) matches the pattern. So if you don't want that, take them away.

like image 127
Marc Gravell Avatar answered Jul 03 '26 20:07

Marc Gravell