package URL;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Test1{
public static void main(String[]args){
String regex = "\\w+@\\w+\\.(com\\.cn)|\\w+@\\w+\\.(com|cn)";
/*
\w代表[a-zA-z0-9_],之所以寫成\\w是因爲\有轉義的意思,所以要輸出 \必須得寫成\\
+ 代表可以有一次或者多次
\\.就代表着.,因爲.在正則表達式中代表一個任意的字符,所以要想寫出.來就得要用到轉義字符\
要輸出\就得要寫成\\
()代表着一個組合,例如(com)會去匹配含有com的字符串,而com會去匹配含有c或者o或者m
的字符串
| 代表這或
注意:按照正則表達式去匹配的時候是有優先級的,從左至右,()也可以看做是一
優先級的控制,\\w+@\\w+\\.(com|cn)+ 改爲\\w+@\\w+\\.com|cn+程序會以爲\\w+@\\w+\\.com或者cn
這樣當對[email protected]匹配時下面的程序會輸出cn,而我們的初衷是讓com與cn或
*/
//String regex = "[a-zA-Z0-9_]+[@][a-zA-Z0-9]+([\\.com]|[\\.cn])";
Pattern pattern = Pattern.compile(regex);
String context = "[email protected] ;[email protected];[email protected] "
+";[email protected] ;[email protected]";
Matcher matcher = pattern.matcher(context);
while (matcher.find()) {
System.out.println(matcher.group());
}
}