例子一:
import java.util.regex.Pattern;
public class TestReg {
public static void main(String[] args) {
String[] strs = { "15017508877", "15017508867", "150175088" };
String[] strs2={"yaokangjun@foxmail.com","442834926","442834926@qq.com"};
for (String s : strs) {
if (Pattern.matches("[1]\\d{10}", s)) {
System.out.println(s + " 是手機號碼。");
} else {
System.out.println(s + " 不是手機號碼。");
}
}
for(String s:strs2){
//注意正則表達式裏不要有空格而形成錯誤
if(Pattern.matches("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*.\\w+([-.]\\w+)*", s)){
System.out.println(s+" 是電子郵箱號碼。");
}else{
System.out.println(s+" 不是電子郵箱號碼。");
}
}
}
}
例子二:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestPatternMatcher {
public static String regex="\\d+"; //正則表達式
public static String content="123dadd233abcabc3a456abc44"; //等待匹配的字符串
public static void main(String[] args){
Pattern p=Pattern.compile(regex);
Matcher m=p.matcher(content);
while(m.find()){
System.out.println("第"+m.start()+"位:");
System.out.println(m.group());
}
String c=content.replaceAll(regex, "*"); //替換後的字符串
System.out.println(c);
}
}