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 “me@email.com”, the regex finds a match. If I insert a blank space in the string, like: ” me@mail.com”, 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 = @" me@mail.com";
MatchCollection mcolResults = rEmail.Matches(str);
MessageBox.Show(mcolResults.Count.ToString());
Please let me know what am I doing wrong.
Thank you.
Best regards,
^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.