我想搜索一個字符串的電子郵件地址,但我的正則表達式不起作用,當字符串包含除電子郵件以外的其他字符。意思是,如果我嘗試像「[email protected]」這樣的小字符串,則正則表達式會找到匹配項。如果我在字符串中插入空格,如:「[email protected]」,則正則表達式不會找到電子郵件匹配項。與正則表達式解析字符串
這裏是我的代碼(正則表達式模式是從網上):
string emailpattern = @"^(([^<>()[\]\\.,;:\[email protected]\""]+"
+ @"(\.[^<>()[\]\\.,;:\[email protected]\""]+)*)|(\"".+\""))@"
+ @"((\[[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());
請讓我知道我做錯了。
謝謝。
此致
看看這裏更好的電子郵件正則表達式:http://www.regular-expressions.info/email.html – jtbandes 2010-08-10 05:31:06