public class Main {
public static void main(String[] args) {
/*
* \d 表示任意一个数字 java用\\表示\
* */
String regex = "20\\d\\d";
System.out.println("2019".matches(regex));
System.out.println("2100".matches(regex));
}
}
public class RegexDemo01 {
public static void main(String[] args) {
String re1 = "abc";
System.out.println("abc".matches(re1)); // true
System.out.println("Abc".matches(re1));// false
System.out.println("abcd".matches(re1));//false
}
}
public class RegexDemo02 {
public static void main(String[] args) {
String re1 = "java\\d"; //对应的是java\d
System.out.println("java9".matches(re1)); //true
System.out.println("java10".matches(re1));//false
System.out.println("javac".matches(re1));//false
String re2 = "java\\D";
System.out.println("javax".matches(re2));//true
System.out.println("java#".matches(re2));//ture
System.out.println("java5".matches(re2));//false
}
}
public class RegexDemo03 {
public static void main(String[] args) {
String re = "java|php";
System.out.println("java".matches(re));//true
System.out.println("php".matches(re));//true
System.out.println("go".matches(re));//false
}
}
public class RegexDemo04 {
public static void main(String[] args) {
String re = "learn\\s(java|php|go)"; // /s 匹配空格或tab
System.out.println("learn java".matches(re));//true
System.out.println("learn php".matches(re));//true
System.out.println("learn go".matches(re));//true
}
}
// 分组匹配
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexDemo05 {
public static void main(String[] args) {
Pattern p = Pattern.compile("(\\d{3,4})\\-(\\d{7,8})");
Matcher m = p.matcher("010-12345678");
if (m.matches()) {
String g1 = m.group(1);
String g2 = m.group(2);
System.out.println(g1);
System.out.println(g2);
} else {
System.out.println("匹配失败!");
}
}
}
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("(\\d{3,4})\\-(\\d{7,8})");
pattern.matcher("010-12345678").matches(); // true
pattern.matcher("021-123456").matches(); // true
pattern.matcher("022#1234567").matches(); // false
// 获得Matcher对象:
Matcher matcher = pattern.matcher("010-12345678");
if (matcher.matches()) {
String whole = matcher.group(0); // "010-12345678", 0表示匹配的整个字符串
String area = matcher.group(1); // "010", 1表示匹配的第1个子串
String tel = matcher.group(2); // "12345678", 2表示匹配的第2个子串
System.out.println(area);
System.out.println(tel);
}