I have some emails in the form:
staticN123@sub1.mydomain.com
staticN456@sub2.mydomain.com
staticN789@sub3-sub开发者_JAVA百科.mydomain.com
The dynamic is the number after the (N or M or F) character, and the subDomain between the @ and mydomain.com
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.
staticN([0-9]+)@.+\.mydomain\.com
instead of [0-9]+
you can also use \d+
which is the same.
the .+
after the @ could match too much. eventually you'd like to replace that with [^\.]+
to exclude sub.sub domains.
update:
^staticN(\d+)@[a-z0-9_-]+\.mydomain\.com$
adding ^
and $
to match start and end of the search string to avoid false match to e.g. somthingwrong_staticN123@sub.mydomain.com.xyz
you can test this regexp here link to 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 );
精彩评论