1、简单认识正则表达式的概念
print("abc".matches("..."));//true
print("a8729a".replaceAll("\\d", "-"));//a----a
Pattern p = Pattern.compile("[a-z]{3}");
Matcher m = p.matcher("fgh");
print(m.matches());//true
print("fgha".matches("[a-z]{3}"));//false
2、初步认识. * + ? {n,m}
print("a".matches("."));//true
print("aa".matches("aa"));//true
print("aaaa".matches("a*"));//true 0个或多个
print("aaaa".matches("a+"));//true 1个或多个
print("".matches("a*"));// true
print("aaaa".matches("a?"));//false 0个或1个
print("".matches("a?")); //true
print("a".matches("a?"));//true
print("214523145234532".matches("\\d{3,100}"));//true at least 3 but not more than 100 times
print("192.168.0.aaa".matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"));//false
print("192".matches("[0-2][0-9][0-9]"));//true
3、范围
print("a".matches("[abc]"));//true
print("a".matches("[^abc]"));//false
print("A".matches("[a-zA-Z]"));//true
print("A".matches("[a-z]|[A-Z]"));//true
print("A".matches("[a-z[A-Z]]"));//true
print("R".matches("[A-Z&&[RFG]]"));//true
4、认识\s \w \d \S \W \D
print(" \n\r\t".matches("\\s{4}"));//true
print(" ".matches("\\S"));//false
print("a_8".matches("\\w{3}"));//w is a word character [a-zA-Z_0-9] true
print("abc888&^%".matches("[a-z]{1,3}\\d+[&^#%]+"));//true
print("\\".matches("\\\\"));//true
5、boundary and whitelines
print("hello sir".matches("^h.*")); //true
print("hello sir".matches(".*ir$"));//true
print("hello sir".matches("^h[a-z]{1,3}o\\b.*"));//true
print("hellosir".matches("^h[a-z]{1,3}o\\b.*"));//false
print(" \n".matches("^[\\s&&[^\\n]]*\\n$"));//true
print("aaa 8888c".matches(".*\\d{4}.")); //true
print("aaa 8888c".matches(".*\\b\\d{4}.")); //true
print("aaa8888c".matches(".*\\d{4}."));//true
print("aaa8888c".matches(".*\\b\\d{4}."));//false
6、email
print("asdfasdfsafsf@dsdfsdf.com".matches("[\\w[.-]]+@[\\w[.-]]+\\.[\\w]+"));
7、matches find lookingAt
attern p = Pattern.compile("\\d{3,5}");
String s = "123-34345-234-00";
Matcher m = p.matcher(s);
print(m.matches());//false
m.reset();
print(m.find());//true
print(m.start() + "-" + m.end());//0-3
print(m.find());//true
print(m.start() + "-" + m.end());//4-9
print(m.find());//true
print(m.start() + "-" + m.end());//10-13
print(m.find());//false
print(m.lookingAt());//always from beggining true
print(m.lookingAt());true
print(m.lookingAt());true
print(m.lookingAt());true
8、replacement
Pattern p = Pattern.compile("java", Pattern.CASE_INSENSITIVE);//大小写不敏感
Matcher m = p.matcher("java Java JAVa JaVa IloveJAVA you hateJava afasdfasdf");
StringBuffer buf = new StringBuffer();
int i=0;
while(m.find()) {
i++;
if(i%2 == 0) {
m.appendReplacement(buf, "java");//第偶数个转换为小写
} else {
m.appendReplacement(buf, "JAVA");//第奇数个转换为大写
}
}
m.appendTail(buf);//把最后的字符串追加上
print(buf);
9、group
Pattern p = Pattern.compile("(\\d{3,5})([a-z]{2})");
String s = "123aa-34345bb-234cc-00";
Matcher m = p.matcher(s);
while(m.find()) {
print(m.group());//123aa 34345bb 234cc
}