Pattern class and Matcher class of regular expressions in Java

Source: Internet
Author: User

===================================================================================================
Pattern class Description
---------------------------------------------------------------------------------------------------
A regular expression specified as a string must first be compiled as an instance of the pattern class. You can then use the resulting pattern to create the Matcher object,
Depending on the regular expression, the object can match any sequence of characters. All States involved in performing a match reside in the match.
So multiple matches can share the same pattern.
Therefore, the typical call order is
Pattern p = pattern.compile ("A*b");
Matcher m = P.matcher ("Aaaaab");
Boolean B = m.matches ();
The matches method can be easily defined through the pattern class when only one regular expression is used. This method compiles an expression and, in a single
Matches the input sequence in the call. Statement
Boolean B = pattern.matches ("A*b", "Aaaaab");
is equivalent to the three statements above, although it is inefficient for duplicate matches because it does not allow reuse of compiled schemas.
Instances of this class are immutable and can be used safely by multiple concurrent threads. It is not safe for an instance of the Matcher class to be used for this purpose.
===================================================================================================
Matcher class Description
---------------------------------------------------------------------------------------------------

Creates a match from the pattern by invoking the Matcher method of the pattern. After you create a match, you can use it to perform three different matching operations:

The 1 matches method attempts to match the entire input sequence with the pattern.
(Note: When you call the string's matches () method, you are actually calling the static method matches () of pattern. That's equivalent
Tune the Matcher matches (), so the entire input sequence matches the pattern.

2 Lookingat try to match the input sequence from scratch with the pattern.

3 The Find method scans the input sequence for the next subsequence that matches the pattern.

It is not safe for instances of this class to be used with multiple concurrent threads.
=================================================================================================== Test Code Package  test;       import java.util.regex.matcher;    import java.util.regex.pattern;      /**     * java Two important classes in the application of regular expressions: pattern and Matcher     *   @author  fhd001     */   public class patternandmatchertest {           public static void main (String[] args)  {                        /*             *  Common calls             */                &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;PATTERN&NBSP;P1&NBSP;=&NBsp Pattern.compile ("A*b");                         String str1 =  "Aaaab";            matcher m1 = p1.matcher (STR1);            boolean b1 = m1.matches ();            system.out.println (B1);                         String str2 =  "B";            matcher m2 = p1.matcher (STR2);            boolean b2 = m2.matches ();            system.out.println (B2);             &Nbsp;                       /*             *  another call              *  is equivalent to the above statement, although it is inefficient for duplicate matches because it does not allow reuse of compiled schemas.               *  But it can be used safely by multiple concurrent threads, and the above call is not secure.             */            boolean b3 = pattern.matches ("A*b",  "Aaab");            system.out.println (B3);                       Pattern method for the   //pattern class: Returns a string representation of the matching mode from an instance of the patterns class             string pattern1 = p1.pattern ();            system.out.println (PATTERN1);                       Split method of   //pattern class            string[]arr1 =  p1.split ("Rrrrraaabccccaaaaab");            for  (STRING&NBSP;STRING&NBSP;:&NBSP;ARR1)  {               system.out.println ( string+ ">>>>");            }                                      /*             * matcher Class             *  &NBsp;           * matches Method:         method attempts to match the entire input sequence with the pattern             *  Lookingat method:  try to match the input sequence from scratch with the pattern, similar to the  matches  method,              *                    This method always starts at the beginning of the zone, and unlike it, it does not need to match the entire region.               * find Method:     The        method scans the input sequence to find the next subsequence that matches the pattern              */           String str3 =  " Aabbcccaaaaaeeeaaaaaaaaagggga ";            pattern p3 = pattern.compile ("A +");            matcher m3 = p3.matcher (STR3);                                                  boolean bo4 = m3.matches ();            system.out.println ("matches method:  " +bo4);                                            /*             * lookingat method, which matches the first character from the beginning, and the match succeeds and does not continue to match.             *  starting with the first character, the match fails and does not continue to match. No need to match the entire sequence              */   &NBsp;       boolean bo5 = m3.lookingat ();            if (bo5) {         The        //group method (without parameters) returns a matching substring.                system.out.println (" Lookingat method:   "+m3.group ());            }                                                  //find Method: Find a matching substring, You will continue to find the next substring.            while (M3.find ()) {                system.out.println ("Find Method:  " +m3.group ());    &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}                                      /*             *  The group method with parameters differs from the group method with no parameters             *  Group method with no parameters: The Find method matches the subsequence of the Lookingat method (demo above)             *  The group method with parameters:  returns the input subsequence captured by a given group during a previous matching operation.             */            String str6 =  "AAABBBCCC";            pattern p5 = pattern.compile (+) ( B +) (c+) ");            matcher m5 = p5.matcher (STR6);             boolean boo = m5.matches ();            if (Boo) {                int k = m5.groupcount () +1;//plus 1 is to add the entire character sequence of the 0 subscript, It also serves as a set of 0 subscript positions.                if (k>0) {                   for (int i =0;i<k;i++) {                        system.out.println (M5.group (i));                    }                }             }       &NBSP}   }  

Package test;
Import Java.util.regex.Matcher;

Import Java.util.regex.Pattern; Two important classes that use regular expressions in/** * Java: pattern and Matcher * @author fhd001/public class Patternandmatchertest {public static void
		
		Main (string[] args) {/* * Common call/pattern P1 = Pattern.compile ("A*b");
		String str1 = "Aaaab";
		Matcher m1 = P1.matcher (STR1);
		Boolean B1 = M1.matches ();
		
		System.out.println (B1);
		String str2 = "B";
		Matcher m2 = p1.matcher (str2);
		Boolean b2 = M2.matches ();
		
		
		System.out.println (B2); 
		 * * Another call * is equivalent to the above statement, although it is inefficient for duplicate matches because it does not allow reuse of compiled schemas.
		 * But it can be used safely by multiple concurrent threads, and the above call is not secure.
		* * Boolean b3 = pattern.matches ("A*b", "Aaab");
		
		SYSTEM.OUT.PRINTLN (B3);
		Pattern method: A string pattern1 = P1.pattern () that returns the matching mode from an instance of the patterns class;
		
		System.out.println (PATTERN1);
		The split method of pattern class string[]arr1 = P1.split ("Rrrrraaabccccaaaaab");
		for (String string:arr1) {System.out.println (string+ ">>>>"); } * * MATCHer class * * Matches method: Method attempts to match the entire input sequence with the pattern * Lookingat method: Try to match the input sequence from scratch with the pattern, similar to the matches method, * This method always starts at the beginning of the zone; 
		 The difference is that it does not need to match the entire area.
		* Find Method: Method scans the input sequence to look for the next subsequence that matches the pattern/String STR3 = "Aabbcccaaaaaeeeaaaaaaaaagggga";
		Pattern P3 = Pattern.compile ("A +");
		
		
		
		Matcher m3 = p3.matcher (STR3);
		Boolean Bo4 = M3.matches ();
	
		
		
		System.out.println ("matches method:" +bo4);
		* * * Lookingat method, matching from the first character, the match is successful no longer continue to match, * starting with the first character, the match fails, and does not continue to match. Do not need to match the entire sequence * * Boolean BO5 = M3.lookingat ();
			The IF (BO5) {//group method (without parameters) returns a matching substring.
		System.out.println ("Lookingat Method:" +m3.group ());
		//find method: Finds a matching substring and continues to find the next substring.
		while (M3.find ()) {System.out.println ("Find Method:" +m3.group ()); }/* * The group method with parameters differs from group method without parameters * Group method without parameters: The Find method matches the Lookingat (shown above) with a parameter group method: Returns the previous match
		 An input subsequence captured by a given group during an operation.
		*/String STR6 = "AAABBBCCC";
		Pattern P5 = Pattern.compile ("(A +) (b +) (c+)");
		Matcher M5 = P5.matcher (STR6); Boolean Boo= M5.matches ();
			if (boo) {int k = M5.groupcount () +1;//plus 1 adds the entire character sequence of the 0 subscript, which also acts as a set of 0 subscript positions.
				if (k>0) {for (int i=0;i<k;i++) {System.out.println (M5.group (i));
 }
			}
		}
	}
}

  Result code true    true    true    a*b    rrrrr>>>>    C Ccc>>>>    matches method:   false    Lookingat method:   aa    Find method:   aaaaa    Find method:   aaaaaaaaa    Find method:   a    AAABBBCCC    AAA    BBB    ccc  

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.