简体   繁体   English

使用特殊的电子邮件正则表达式

[英]Using a special email regular expression

I have some emails in the form: 我有一些电子邮件的形式:

staticN123@sub1.mydomain.com
staticN456@sub2.mydomain.com
staticN789@sub3-sub.mydomain.com

The dynamic is the number after the (N or M or F) character, and the subDomain between the @ and mydomain.com 动态值是(N,M或F)字符后的数字,以及@和mydomain.com之间的subDomain。

I want to make a regular expression that matches this form in a string, and if it's a match, get the number after the N character. 我想做一个正则表达式来匹配此形式的字符串,如果匹配,则获取N字符后的数字。

staticN([0-9]+)@.+\.mydomain\.com

instead of [0-9]+ you can also use \\d+ which is the same. 除了[0-9]+您还可以使用\\d+ the .+ after the @ could match too much. @之后的.+可能匹配过多。 eventually you'd like to replace that with [^\\.]+ to exclude sub.sub domains. 最终,您希望将其替换为[^\\.]+以排除sub.sub域。

update: 更新:

^staticN(\d+)@[a-z0-9_-]+\.mydomain\.com$

adding ^ and $ to match start and end of the search string to avoid false match to eg somthingwrong_staticN123@sub.mydomain.com.xyz 添加^$以匹配搜索字符串的开始结尾 ,以避免与例如somthingwrong_staticN123@sub.mydomain.com.xyz的错误匹配

you can test this regexp here link to rubular 您可以在此处测试此正则表达式链接到rubular

-- -

applying changes discussed in comments below: 应用以下注释中讨论的更改:

^(?:.+<)?static[NMF](\d+)@[a-z0-9_-]+\.mydomain\.com>?$

code example to answer the question in one of the comments: 在注释之一中回答问题的代码示例:

// input
String str = "reply <staticN123@sub1.mydomain.com";
// example 1
String nr0 = str.replaceAll( "^(?:.+<)?static[NMF](\\d+)@[a-z0-9_-]+\\.mydomain\\.com>?$", "$1" );
System.out.println( nr0 );
// example 2 (precompile regex is faster if it's used more than once afterwards)
Pattern p = Pattern.compile( "^(?:.+<)?static[NMF](\\d+)@[a-z0-9_-]+\\.mydomain\\.com>?$" );
Matcher m = p.matcher( str );
boolean b = m.matches();
String nr1 = m.group( 1 );  // m.group only available after m.matches was called
System.out.println( nr1 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM