I only learned about regular expressions in (1) and (2). Today I have learned more about the application of regular expressions in the string class, mainly in matches (), split (), replace (), replaceall (), replacefirst, and other methods.
Now let's take a look at their definitions in jdk1.6:
Matches
Public Boolean matches (string RegEx)
Indicates whether the string matches the given regular expression.
Replace
Public String Replace (char oldchar, char newchar)
Returns a new string, which is replaced by newchar
Split
Public String [] Split (string RegEx, int limit)
Splits the string based on the given regular expression.
Public String [] Split (string RegEx)
Split this string based on the matching of the given regular expression. The function of this method is to call the Two-Parameter split method using the given expression and the limit parameter 0. Therefore, the resulting array does not contain trailing null strings.
Replaceall
Public String replaceall (string RegEx, string replacement)
Replace all the substrings matching the given regular expression with the given replacement.
Replacefirst
Public String replacefirst (string RegEx, string replacement)
Replace the string with the given replacement to match the first substring of the given regular expression.
For details about the above methods, refer to JDK. I will not talk about them here. The following example shows how to use these methods.
Public Class Testregex {
Public Static Void Main (string [] ARGs ){
String Str = " Lovefeel2004@126.com " ;
// Matches () Usage
String regex1 = " ^ [A-zA-Z0-9 _-] + @ [a-zA-Z0-9 _-] + [.] (net) | (COM) | (com.cn) $ " ;
Boolean B;
B = Str. Matches (regex1 );
P (B + " \ N " );
// Spilt () Usage
String [] split1 = Str. Split ( " @ " );
P ( " Use @ to split the STR string: " );
For (String S: split1 ){
P (S + " " );
}
String [] split2 = Str. Split ( " @ | \\. " );
P ( " \ N use @ or. to separate the STR string: " );
For (String S: split2 ){
P (S + " " );
}
// Replace (), replaceall (), replacefirst () Usage
P ( " \ N use # to replace the STR after: " );
P (Str. Replace ( " @ " , " # " ) + " \ N " );
P ( " Use D to replace STR after O: " );
P (Str. replaceall ( " O " , " D " ) + " \ N " );
P ( " Replace STR after the first O with D: " );
P (Str. replacefirst ( " O " , " D " ) + " \ N " );
}
// Print Method
Public Static Void P (Object O ){
System. Out. Print (O );
}
}
Result:
Next, we will learn about the java. util. RegEx package class. After all, string only provides simple regular expression functions.
If this article is incorrect, please correct it !!!