Public Pattern. matcher (CharSequence input) gets a comparator (matcher) for comparing character sequences with input)
Public static boolean Pattern. matches (String regex, CharSequence input)
Find the pattern corresponding to the regular expression regex in the character sequence input,
Equivalent to Pattern. compile (regex). matcher (input). matches ();
If regex needs to be used multiple times, use the following format to save time for regex compilation.
Pattern partn = Pattern. compile (regex );
Partn. matcher (input). matches ();
The parameter of match () is generally a regular expression. Now we have two regular expressions. You can try them out.
Regular expression 1: applicable to any form of string,
Here, LikeType is the string to be matched, patten is the generated regular expression, and sourceStr is an existing string. Determine whether sourceStr meets the regular expression of LikeType.
Public static void main (String [] args ){
// TODO Auto-generated method stub
String likeType = "23 ";
String pattern = "[a-zA-Z0-9] * [" + likeType + "] {1} [a-zA-Z0-9] *";
String sourceStr = "adfjaslfj23ldfalsf ";
System. out. println (sourceStr. matches (likeType ));
}
Regular expression 2: String matching at a fixed position, which is similar to the above, but different from the regular expression.
Public static void main (String [] args ){
// TODO Auto-generated method stub
String likeType = "%%% 23% % *";
String sourceStr = "423236664 ";
LikeType = likeType. replaceAll ("%", "\ d"). replaceAll ("*", "\ d *");
System. out. println (likeType );
System. out. println (sourceStr. matches (likeType ));
}
Regular expression of phone number
Public class Main {
Public static void main (String args []) {
String phone = "(111)-111-1111 ";
String phoneNumberPattern = "(d -)? (D {3 }-)? D {3}-d {4 }";
System. out. println (phone. matches (phoneNumberPattern ));
}
}
The match method is relatively simple, but it is absolutely practical. Therefore, it is particularly important to master the usage and write regular expressions.
Mailbox No.
Public class Main {
Public static void main (String [] ){
String zip = "1234-123 ";
String zipCodePattern = "d {5} (-d {4 })? ";
Boolean retval = zip. matches (zipCodePattern );
}
}
Regular date validity
Public class Main {
Public static void main (String [] argv) throws Exception {
Boolean retval = false;
String date = "12/12/1212 ";
String datePattern = "d {1, 2}-d {1, 2}-d {4 }";
Retval = date. matches (datePattern );
}
}