總的來說博客中講的太少了,還是要看編程思想,裏面有關於這部分非常全面的講解。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Ans {
public static void main(String[] args) {
test1();
test3();
test5();
}
static void test1() {
//注意\d匹配數字,\D匹配非數字
//{n}爲匹配n個,{n,m}匹配n到m個,{n,}匹配至少n個
//使用String.matches反覆匹配一個表達式會不斷創建相同的Pattern,導致一些性能上的浪費
String re0 = "\\d",re1 = "\\D",re2 = "\\d{3}",re3 = "\\d{2,4}",re4 = "\\d{2,}";
System.out.println("1".matches(re1));
System.out.println("111".matches(re2));
System.out.println("111".matches(re3));
System.out.println("1111111".matches(re4));
}
static void test2() {
// ^爲開頭,$爲結尾
}
static void test3() {
//括號可以在匹配時起到分組的作用
Pattern p = Pattern.compile("(\\d{3})(\\d{2,6})");
Matcher m = p.matcher("112456");
if (m.matches()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
}
}
static void test4() {
//java 默認爲貪婪匹配,加上?變爲勉強型,加上+變爲佔有型(在編程思想中講到)
}
static void test5() {
//再替換時可以使用$來反向匹配
Pattern p = Pattern.compile("([a-z]{2,5})(\\d{1,4})");
Matcher m = p.matcher("adada132 dai3 aod9qeq aoaoddidi44");
System.out.println(m.replaceAll("<a>$1<a><b>$2<b>"));
}
}