Java regular expressions are added since JDK1.4. To solve the problem of string matching before JDK1.4, java is often used. the StringTokenizer class in the util package, or the String split method, but this is not the best method. Therefore, JDK1.4 begins to add a regular expression. In fact, other languages already have regular expressions, regular expressions, such as Perl, PHP, and javascript, are also considered to be one of the top ten most important computer technologies in the future.
The following is an example:
Public class RegEx {
Public static void main (String [] args ){
String regEx1 = "^ [a-zA-Z0-9] {5, 12} $"; // 5-12 usernames can only be letters or numbers
String regEx2 = "^ [a-zA-Z0-9] {6, 16} $"; // a 6-16 user password can only be letters or numbers
String regEx3 = "^ [a-zA-Z0-9 _-] + @ [a-zA-Z0-9 _-] + [.] (net) | (com) $ "; // email verification.
String user = "lovefeel2004 ";
If (user. matches (regEx1) {// matches Regular Expressions for user input verification
System. out. println ("OK ");
} Else {
System. out. println ("usrsname id error ");
}
String password = "123abc456ABC ";
System. out. println (password. matches (regEx2 ));
String email = "lovefeel2004@126.com ";
System. out. println (email. matches (regEx3 ));
}
}
Although the above example is simple, it also implements Regular Expressions and uses the matches () method of the String class to implement the matches () method.
Prototype:
Public boolean matches (String regex)
Indicates whether the string matches the given regular expression.
The str. matches (regex) form that calls this method is identical to the results produced by the following expressions:
Pattern. matches (regex, str)
Parameters:
Regex-Regular Expression used to match this string
Return Value:
Returns true if and only if the string matches the given regular expression.
Throw:
PatternSyntaxException-if the regular expression syntax is invalid
The morning study is here. continue next time. If the above is incorrect, you may wish to give me some advice!