我很难形成一个正则表达式来检查一串随机单词是否包含电子邮件地址。例如:
string str = "Hello, thank you for viewing my ad. Please contact me on the phone number below, or at abcd@gmail.com"
=匹配
string str - "Hello, thank you for viewing my ad. Please contact me on the phone number below"
=不匹配
如何使用正则表达式检查字符串是否包含电子邮件地址?任何帮助都将受到高度赞赏。
答案 0 :(得分:0)
检索电子邮件地址有很多RegEx变体,严格程度不同。只需点击链接,根据您的需要选择合适的链接。 http://www.regular-expressions.info/email.html
对于大多数需求,可以使用下一个模式
Regex pattern = new Regex(@"
\b #begin of word
(?<email> #name for captured value
[A-Z0-9._%+-]+ #capture one or more symboles mentioned in brackets
@ #@ is required symbol in email per specification
[A-Z0-9.-]+ #capture one or more symboles mentioned in brackets
\. #required dot
[A-Z]{2,} #should be more then 2 symboles A-Z at the end of email
)
\b #end of word
", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
var match = pattern.Match(input);
if (match.Success)
{
var result = match.Groups["email"];
}
请记住,此模式并非100%可靠。它适用于像
这样的字符串string input = "This can be recognized as email heymail@gmail.company.com";
但是在字符串中
string input = "This can't be recognized as email hey@mail@gmail.com";
它捕获&#34; mail@gmail.com"尽管根据规范,这封电子邮件不正确。