In Java, using the pattern class and the Matcher class to find and replace, will you?

Source: Internet
Author: User

Preface in either language, we always use regular expressions to find and replace strings. Not in Java, I once wrote a Web page---regular expression online testing. At that time, I had not started to learn Java, do not know Java support regular expression, so my first solution is to find ways to transfer data to the background, and then use the shell script regular expression to get the matching results. If you do that later, then it's two. Later I studied the following other similar sites, found that even JS files do not have to write, directly write the function in the HTML file can complete this task. One day, I wrote this website out. So, even if it's not a scripting language, it's always good to know the following regular expressions. However, this article does not repeat the regular expression of the syntax, unclear students can go directly to the API document check. This article mainly introduces some methods for finding and replacing using the pattern class and the Matcher class, because these methods are easy to confuse, so share it and welcome the shot bricks. Basic usage The basic process used by the Pattern class and the Matcher class: 1. Import the Java.util.regex package; 2. Generates a Pattern object reference based on your string, such as String str = "abc+", Pattern p = Pattern.compile (str); 3. Call the pattern's Matcher method, pass in a matching string, generate a Matcher object reference, 4. Call the Matcher class for a number of methods to implement functions such as find and replace. As shown in the following example:

Import java.util.regex.*;p Ublic class Testregularexpression {public static void main (string[] args) {String strchars    Equence = "ABCABCABCDEFABC";    String Strregex = "(ABC) +";    Pattern p = pattern.compile (Strregex);    Matcher m = P.matcher (strcharsequence); while (M.find ()) {<span style= ' white-space:pre ' ></span>system.out.println ("Match \" "+ m.group () +" \ "at p    Ositions "+ m.start () +"-"+ (M.end ()-1)); }  }}
Output Result:

Match "ABCABCABC" at positions 0-8match "ABC" at positions 12-14
Program Description: This program is matched in string abcabcabcdefabc by regular expression (ABC) +. and using the Matcher.find () function to find, now just need to know that the find () function can do multiple matches, the Matcher.group () method can return the entire matching result, the start () function returns the starting index of the matching position, end () The multibyte method returns a value that matches the last word, 1. Let's take a detailed look at the differences between Matches,lookingat and find in a few common ways to find them.

Find
    • The matches () method is used to determine whether the entire string matches a regular expression, and only returns true if all matches, otherwise false is returned. But if it is partially matched, it moves the position of the beginning of the match;
    • The Lookingat () method is partially matched, always matches from the first character, the match succeeds no longer matches, the match fails, and the match is not continued;
    • The Find () method, partially matched, starts the match at the current position, finds a matching substring, and moves the next matching position;
    • Reset () method to reset the position that is currently starting to match to the first position on the left.
This can be understood in conjunction with the following example.
Import Java.util.regex.matcher;import Java.util.regex.Pattern; public class Iotest {public static void main (string[] args) {Pattern pattern = Pattern.compile ("\\d{3,5}"); String charsequence = "123-34345-234-00"; Matcher Matcher = Pattern.matcher (charsequence); Although the match failed, but because charsequence inside the "123" and pattern is matched, so the next match from position 4 to start print (Matcher.matches ());//Test Match location Matcher.find (); Print (Matcher.start ()); Use the Reset method to reset the matching position matcher.reset (); First find matches and matches the starting position of the target and match print (Matcher.find ());p rint (Matcher.group () + "-" +matcher.start ());// The second find matches and matches the target and the starting position of the match print (Matcher.find ());p rint (Matcher.group () + "-" +matcher.start ()); The first Lookingat matches and matches the target and the starting position of the match is print (Matcher.lookingat ());p rint (Matcher.group () + "-" +matcher.start ()); The second Lookingat matches and matches the target and the starting position of the match is print (Matcher.lookingat ());p rint (Matcher.group () + "-" +matcher.start ());} public static void print (Object o) {System.out.println (o);}}
Output Result:
false4true123-0true34345-4true123-0true123-0
Replace find always and replace together, Ctrl+f and ctrl+p like McDonald's and KFC Bar, O (∩_∩) o haha ~. Matcher shows the Replacefirst, ReplaceAll, Appendreplacement, and Appendtail methods for replacing the operations, let's look at the differences between these methods.
    • Replacefirst () replaces only the first place to match;
    • ReplaceAll () Replace all matches to the place;
    • Appendreplacement () copies the characters at the replacement position and at the previous position into the stringbuffer;
    • Appendtail () copies the characters after the replacement position to the StringBuffer
See the example below to see it.
: Strings/thereplacements.javaimport java.util.regex.*;p ublic class Thereplacements {private static final String Conststring = "Fat cat, Fat cat, Fat cat, I like.";  public static void Main (string[] args) throws Exception {  Pattern p = pattern.compile ("cat");  Matcher m = P.matcher (conststring);    Replacefirst () replaces only the first place that matches to  System.out.println (M.replacefirst ("Dog"));    ReplaceAll () Replaces all matches to the place  p = pattern.compile ("cat");  m = P.matcher (conststring);    System.out.println (M.replaceall ("Dog"));    Appendreplacement () copies the characters from the replacement position and the previous position to StringBuffer,  //appendtail () copies the characters after the replacement position to StringBuffer  p = Pattern.compile ("cat");  m = P.matcher (conststring);  StringBuffer sb = new StringBuffer ();  while (M.find ()) {  m.appendreplacement (sb, "Dog");  System.out.println (Sb.tostring ());  }   M.appendtail (SB);  System.out.println (Sb.tostring ());}  }
Output Result:

Fat dog, Fat cat, fat cat, I like.fat dog, fat Dog, fat dog, I like.fat dogfat dog, Fat dogfat dog, Fat dog, fat dogfat do g, fat Dog, Fat dog, I like.



In Java, using the pattern class and the Matcher class to find and replace, will you?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.