|
Pattern class:
The pattern method is as follows:
Static pattern compile (string RegEx)
Compile the given regular expression and assign it to the pattern class.
Static pattern compile (string RegEx, int flags)
Same as above, but the flag parameter is added. The optional flag parameters include: Case
Insensitive, multiline, dotall, Unicode case, Canon EQ
Int flags ()
Returns the matching flag parameter of the current pattern.
Matcher (charsequence input)
Generate a matcher object with a given name
Static Boolean matches (string RegEx, charsequence input)
Compile the given regular expression and perform matching on the input string using the regular expression as the modulo. This method is suitable for the regular expression that is used only once, that is, only one matching operation, in this case, you do not need to generate a matcher instance.
String Pattern ()
Returns the regular expression compiled by the patter object.
String [] Split (charsequence input)
Divide the target string according to the regular expression in pattern as a modulo.
String [] Split (charsequence input, int limit)
The purpose of adding the limit parameter is to specify the number of segments to be split. For example, if Limi is set to 2, the target string is split into two segments based on the regular expression.
A regular expression, that is, a string of specific characters, must first be compiled into an instance of the pattern class. This pattern object will use matcher () method to generate a matcher instance.
The matcher instance matches the target String Based on the compiled regular expression. Multiple matcher objects can share one pattern object.
Now let's take a look at a simple example and analyze it to learn how to generate a pattern object and compile a regular expression. Finally, we can split the target string based on this regular expression:
Import java. util. RegEx .*;
Public class replacement {
Public static void main (string [] ARGs) throws exception {
// Generate a pattern and compile a regular expression
Pattern P = pattern. Compile ("[/] + ");
// Use the split () method of pattern to split the string "/"
String [] result = P. Split (
"Kevin has seen" Leon "seveal times, because it is a good film ."
+ "/
Kevin has read "this killer is not too cold" several times, because it is"
+ "Good movies. /Term: Kevin. ");
For (INT I = 0; I <result. length; I ++)
System. Out. println (result [I]);
}
}
Output result:
Kevin has seen "Leon" seveal times, because it is a good film.
Kevin has watched "this killer is not too cold" several times, because it is a good movie.
Term: Kevin.
Obviously, this program segments the string by "/". We will use the following
Split (charsequence input, int
Limit) method to specify the number of segments, the program changed:
Tring [] result = P. Split ("Kevin has seen" Leon "seveal times, because
It is a good film ./
Kevin has watched "this killer is not too cold" several times, because it is a good movie. /Term: Kevin. ", 2 );
The parameter "2" indicates that the target statement is divided into two sections.
The output result is:
Kevin has seen "Leon" seveal times, because it is a good film.
Kevin has watched "this killer is not too cold" several times, because it is a good movie. /Term: Kevin.
From the above example, we can compare the implementation methods of Java. util. RegEx in constructing the pattern object and compiling the specified regular expression with the Jakarta-Oro we introduced in the previous article.
Jakarta-Oro
The package first constructs a patterncompiler class object and then generates a pattern object. Then, the regular expression uses the compile () method of the patterncompiler class to compile the required regular expression and assign it to the pattern class:
Patterncompiler orocom = new perl5compiler ();
Pattern pattern = orocom. Compile ("Regular Expressions ");
Patternmatcher = new perl5matcher ();
However, in the Java. util. RegEx package, we only need to generate a pattern class and directly use its compile () method to achieve the same effect:
Pattern P = pattern. Compile ("[/] + ");
Therefore, it seems that the java. util. RegEx constructor is simpler and easier to understand than Jakarta-Oro.
3. matcher class:
The matcher method is as follows: matcher appendreplacement (stringbuffer Sb,
String replacement)
Replace the current matched substring with the specified substring, and add the substring after the replacement and the string segment after the previous matched substring to a stringbuffer object.
Stringbuffer appendtail (stringbuffer SB)
Add the remaining strings after the last match to a stringbuffer object.
Int end ()
Returns the index position of the last character of the matched substring in the original target string.
.
Int end (INT Group)
Returns the position of the last character of the substring that matches the specified group in the matching mode.
Boolean find ()
Find the next matched substring in the target string.
Boolean find (INT start)
Reset the matcher object and try to find the next matched substring from the specified position in the target string.
String group ()
Returns the content of all substrings that match the Group obtained by the current query.
String group (INT Group)
Returns the content of the substring that matches the specified group.
Int groupcount ()
Returns the number of matched groups obtained by the current query.
Boolean lookingat ()
Checks whether the target string starts with a matched substring.
Boolean matches ()
Try to expand the matching check for the entire target character, that is, the true value is returned only when the entire target string is completely matched.
Pattern pattern ()
Returns the existing matching pattern of the matcher object, that is, the corresponding pattern.
Object.
String replaceall (string replacement)
Replace all substrings in the target string that match the existing mode with the specified string.
String replacefirst (string replacement)
Replace the first substring that matches the existing mode in the target string with the specified substring.
Matcher reset ()
Reset the matcher object.
Matcher reset (charsequence input)
Reset the matcher object and specify a new target string.
Int start ()
Returns the position of the starting character of the substring in the original target string.
Int start (INT Group)
Returns the position of the first character in the original target string of the substring that matches the specified group.
(Is it hard to understand the explanation of the method? Don't worry. It will be easier to understand in the future with examples)
A matcher instance is used to search for the target string based on the existing pattern (that is, the regular expression compiled by a given pattern, all input to matcher is provided through the charsequence interface, so as to support matching of the data provided from a wide range of data sources.
Let's take a look at the usage of each method:
★Matches ()/lookingat ()/find ():
A matcher object is generated by a pattern object calling its matcher () method. Once the matcher object is generated, it can perform three different matching search operations:
The matches () method tries to expand the matching check for the entire target character, that is, the true value is returned only when the entire target string is completely matched.
Lookingat
() The method checks whether the target string starts with a matched substring.
The find () method tries to find the next matched substring in the target string.
All three methods return a Boolean value to indicate whether the operation is successful or not.
★Replaceall ()/appendreplacement ()/appendtail ():
The matcher class also provides four methods to replace matched substrings with specified strings:
Replaceall ()
Replacefirst ()
Appendreplacement ()
Appendtail ()
Replaceall () and replacefirst () are easy to use. Please refer to the explanation of the above method. We mainly focus on the appendreplacement () and appendtail () methods.
Appendreplacement (stringbuffer Sb, string replacement)
Replace the current matched substring with the specified string, and add the replaced substring and the string segment following the previous matched substring to a stringbuffer object, while appendtail (stringbuffer
SB)
The method adds the remaining strings after the last matching operation to a stringbuffer object.
For example, if there is a string fatcatfatcatfat and the regular expression pattern is "cat" and appendreplacement (SB, "dog") is called after the first match, then stringbuffer
The content of Sb is fatdog, that is, CAT in fatcat is replaced with dog, and the content before matching the substring is added to sb. After the second match, appendreplacement (SB, "dog"), then the Sb content becomes fatdogfatdog. If you call appendtail (SB) Again, the SB final content will be fatdogfatdogfat.
Still a little fuzzy? Let's look at a simple program:
// Change "Kelvin" in the sentence to "Kevin" in this example"
Import java. util. RegEx .*;
Public class matchertest {
Public static void main (string [] ARGs)
Throws exception {
// Generate the pattern object and compile a simple regular expression "Kelvin"
Pattern P = pattern. Compile ("Kevin ");
// Use the matcher () method of the pattern class to generate a matcher object
Matcher M = P. matcher ("Kelvin Li and Kelvin Chan are both working in
Kelvin Chen's kelvinsoftshop company ");
Stringbuffer sb = new stringbuffer ();
Int I = 0;
// Use the find () method to find the first matched object
Boolean result = M. Find ();
// Use loops to find and replace all Kelvin in the sentence and then add the content to sb.
While (result ){
I ++;
M. appendreplacement (SB, "Kevin ");
System. Out. println ("the" + I + "times after the matching, the Sb content is:" + Sb );
// Continue searching for the next matching object
Result = M. Find ();
}
// Call the appendtail () method to add the remaining strings after the last match to sb;
M. appendtail (SB );
System. Out. println ("the final content of Sb after calling M. appendtail (SB) is:" +
SB. tostring ());
}
}
The final output result is:
After 1st matches, the Sb content is: Kevin
After 2nd matches, the Sb content is: Kevin Li and Kevin
After 3rd matches, the Sb content is: Kevin Li and Kevin Chan are both
Working in Kevin
After 4th matches, the Sb content is: Kevin Li and Kevin Chan are both
Working in Kevin Chen's Kevin
The final content of Sb after calling M. appendtail (SB) is: Kevin Li and Kevin Chan
Are both working in Kevin Chen's kevinsoftshop company.
Check whether the above routine is more clear about the use of appendreplacement () and appendtail () methods. If you are not sure, you 'd better write a few lines of code to test it yourself.
★Group ()/group (INT group)/groupcount ():
The find () method indicates whether a matching string exists. The group () method returns the matching string. The execution result of the program is as follows:
Justin's mobile phone number: 0939-100391
Momor mobile phone: 0939-666888
Bush's mobile phone number: 0939-550391
The following uses pattern and matcher to rewrite example 6.9, so that the program can return a string that conforms to the regular expression, rather than returning a string that does not conform to the regular expression.
** Example 6.12regularexpressiondemo2.java
Import java. util. RegEx .*;
Public class regularexpressiondemo2 {
Public static void main (string [] ARGs ){
String text = "abcdebcadxbc ";
Pattern pattern = pattern. Compile (". BC ");
Matcher = pattern. matcher (text );
While (matcher. Find ()){
System. Out. println (matcher. Group ());
}
System. Out. println ();
}
}
Style = 'font-family: '> execution result:
ABC
EBC
Xbc
Address: http://hi.baidu.com/gengshenspirit/blog/item/edb8a954df5825173a293592.html |