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