If you need to represent a set of strings according to specific rules, use regular expressions. Regular expressions can use strings to describe rules and be used to match strings
Java provides the standard library java.util.regex
, which can easily use regular expressions.
If the regular expression has special characters, it needs to be escaped with \
, which will be mentioned later.
number
Match numbers
Use \d
to match one digit. The writing method is \\d
,
String regex1 = "\\d\\d\\d";
System.out.println("110".matches(regex1)); // true
System.out.println("119".matches(regex1)); // true
System.out.println("120".matches(regex1)); // true
System.out.println("1200".matches(regex1)); // false
System.out.println("12F".matches(regex1)); // false
Whether it is an 11-digit number, a common scenario is to determine the mobile phone number.
String regex2 = "\\d{11}";
System.out.println("12345678900".matches(regex2));// true
System.out.println("123456789001".matches(regex2));// false
System.out.println("1234567890a".matches(regex2));// false
System.out.println("A2345678900".matches(regex2));// false
Match non-digits
Use \D
to match a non-digit, the writing method is \\D
,
String regexD = "\\D\\D";
System.out.println("66".matches(regexD));// false
System.out.println("1*".matches(regexD));// false
System.out.println("1@".matches(regexD));// false
System.out.println("1#".matches(regexD));// false
System.out.println("$$".matches(regexD));// true
Match numbers 0-9
Use [0-9]
to match one digit,
String regexd09 = "[0-9][0-9]";
System.out.println("11".matches(regexd09));// true
System.out.println("110".matches(regexd09));// false
System.out.println("1A".matches(regexd09));// false
System.out.println("AA".matches(regexd09));// false
Extension, use [5-8] to match numbers 5-8,
String regexd58 = "[5-8][5-8]";
System.out.println("55".matches(regexd58));// true
System.out.println("88".matches(regexd58));// true
System.out.println("66".matches(regexd58));// true
System.out.println("59".matches(regexd58));// false
System.out.println("48".matches(regexd58));// false