Java Tutorial/Regular Expressions/Matcher

Материал из Java эксперт
Перейти к: навигация, поиск

Create a Matcher from Pattern

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexDemo {

 private static String REGEX = "a*b";
 private static String INPUT = "aabfooaabfooabfoob";
 private static String REPLACE = "-";
 public static void main(String[] args) {
   Pattern p = Pattern.rupile(REGEX);
   Matcher m = p.matcher(INPUT); // get a matcher object
   StringBuffer sb = new StringBuffer();
   while (m.find()) {
     m.appendReplacement(sb, REPLACE);
   }
   m.appendTail(sb);
   System.out.println(sb.toString());
 }

}</source>





Demonstrates the usage of the Matcher.reset() method

   <source lang="java">

import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainClass {

 public static void main(String args[]) {
   Pattern p = Pattern.rupile("\\d");
   Matcher m1 = p.matcher("01234");
   while (m1.find()) {
     System.out.println("\t\t" + m1.group());
   }
   m1.reset();
   System.out.println("After resetting the Matcher");
   while (m1.find()) {
     System.out.println("\t\t" + m1.group());
   }
 }

}</source>





Find the starting point of the first "Bond"

   <source lang="java">

import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainClass {

 public static void main(String args[]) {
   String candidateString = "My name is Bond. James Bond.";
   String matchHelper[] = { "          ^", "                      ^" };
   Pattern p = Pattern.rupile("Bond");
   Matcher matcher = p.matcher(candidateString);
   // Find the starting point of the first "Bond"
   matcher.find();
   int startIndex = matcher.start();
   System.out.println(candidateString);
   System.out.println(matchHelper[0] + startIndex);
 }

}</source>





lookingAt vs matches

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatchesLooking {

 private static final String REGEX = "foo";
 private static final String INPUT = "fooooooooooooooooo";
 private static Pattern pattern;
 private static Matcher matcher;
 public static void main(String[] args) {
   // Initialize
   pattern = Pattern.rupile(REGEX);
   matcher = pattern.matcher(INPUT);
   System.out.println("Current REGEX is: " + REGEX);
   System.out.println("Current INPUT is: " + INPUT);
   System.out.println("lookingAt(): " + matcher.lookingAt());
   System.out.println("matches(): " + matcher.matches());
 }

}</source>





Matcher.appendReplacement method

   <source lang="java">

import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainClass {

 public static void main(String args[]) {
   Pattern p = Pattern.rupile("(\\w+) (\\w+)");
   StringBuffer sb = new StringBuffer();
   String candidateString = "Jack Lee";
   String replacement = "$2, $1";
   Matcher matcher = p.matcher(candidateString);
   matcher.matches();
   matcher.appendReplacement(sb, replacement);
   System.out.println(sb.toString());
 }

} //</source>



Lee, Jack


Matcher.end(int) method

   <source lang="java">

import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainClass {

 public static void main(String args[]) {
   Pattern p = Pattern.rupile("B(on)d");
   String candidateString = "My name is Bond. James Bond.";
   String matchHelper[] = { "               ^", "              ^", "                           ^",
       "                          ^" };
   Matcher matcher = p.matcher(candidateString);
   // Find the end point of the first "B(ond)"
   matcher.find();
   int endIndex = matcher.end(0);
   System.out.println(candidateString);
   System.out.println(matchHelper[0] + endIndex);
 }

}</source>





Matcher.find(int) method

   <source lang="java">

import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainClass {

 public static void main(String args[]) {
   Pattern p = Pattern.rupile("java", Pattern.CASE_INSENSITIVE);
   String candidateString = "Java. java JAVA jAVA";
   Matcher matcher = p.matcher(candidateString);
   // display the latter match
   System.out.println(candidateString);
   matcher.find(11);
   System.out.println(matcher.group());
   // display the earlier match
   System.out.println(candidateString);
   matcher.find(0);
   System.out.println(matcher.group());
 }

} /*

  • /</source>



Java. java JAVA jAVA
JAVA
Java. java JAVA jAVA
Java


Matcher.find method

   <source lang="java">

import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainClass {

 public static void main(String args[]) {
   Pattern p = Pattern.rupile("Java");
   String candidateString = "Java Java Java.";
   // Attempt to match the candidate String.
   Matcher matcher = p.matcher(candidateString);
   // loop though and display all matches
   while (matcher.find()) {
     System.out.println(matcher.group());
   }
 }

}</source>





Matcher.group() method

   <source lang="java">

import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainClass {

 public static void main(String args[]) {
   // create a Pattern
   Pattern p = Pattern.rupile("Bond");
   // create a Matcher and use the Matcher.group() method
   String candidateString = "My name is Bond. James Bond.";
   Matcher matcher = p.matcher(candidateString);
   // extract the group
   matcher.find();
   System.out.println(matcher.group());
 }

}</source>





Matcher.LookingAt method

   <source lang="java">

import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainClass {

 public static void main(String args[]) {
   Pattern p = Pattern.rupile("Java");
   String candidateString_1 = "Java is Java";
   String candidateString_2 = "J2SE is Java";
   String candidateString_3 = "J2SEisJava";
   Matcher matcher = p.matcher(candidateString_1);
   String msg = ":" + candidateString_1 + ": matches?: ";
   System.out.println(msg + matcher.lookingAt());
   matcher.reset(candidateString_2);
   msg = ":" + candidateString_2 + ": matches?: ";
   System.out.println(msg + matcher.lookingAt());
   matcher.reset(candidateString_3);
   msg = ":" + candidateString_3 + ": matches?: ";
   System.out.println(msg + matcher.lookingAt());
 }

}</source>





Matcher.matches method

   <source lang="java">

import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainClass {

 public static void main(String args[]) {
   Pattern p = Pattern.rupile("J2SE");
   String candidateString_1 = "j2se";
   String candidateString_2 = "J2SE ";
   String candidateString_3 = "J2SE";
   Matcher matcher_1 = p.matcher(candidateString_1);
   Matcher matcher_2 = p.matcher(candidateString_2);
   Matcher matcher_3 = p.matcher(candidateString_3);
   String msg = ":" + candidateString_1 + ": matches?: ";
   System.out.println(msg + matcher_1.matches());
   msg = ":" + candidateString_2 + ": matches?: ";
   System.out.println(msg + matcher_2.matches());
   msg = ":" + candidateString_3 + ": matches?: ";
   System.out.println(msg + matcher_3.matches());
 }

} /*

  • /</source>



:j2se: matches?: false
:J2SE : matches?: false
:J2SE: matches?: true


Matcher.pattern method

   <source lang="java">

import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainClass {

 public static void main(String args[]) {
   Pattern p = Pattern.rupile("\\d");
   Matcher m1 = p.matcher("55");
   Matcher m2 = p.matcher("fdshfdgdfh");
   System.out.println(m1.pattern() == m2.pattern());
 }

}</source>





Matcher.replaceAll method

   <source lang="java">

import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainClass {

 public static void main(String args[]) {
   Pattern p = Pattern.rupile("(i|I)ce");
   String candidateString = "Ice. ice Ice Ice.";
   Matcher matcher = p.matcher(candidateString);
   String tmp = matcher.replaceAll("Java");
   System.out.println(tmp);
 }

}</source>





Matcher.reset(CharSequence) method

   <source lang="java">

import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainClass {

 public static void main(String args[]) {
   String output = "";
   Pattern p = Pattern.rupile("\\d");
   Matcher m1 = p.matcher("01234");
   while (m1.find()) {
     System.out.println("\t\t" + m1.group());
   }
   m1.reset("56789");
   System.out.println("After resetting the Matcher");
   while (m1.find()) {
     System.out.println("\t\t" + m1.group());
   }
 }

}</source>





Matcher.start() method

   <source lang="java">

import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainClass {

 public static void main(String args[]) {
   String candidateString = "My name is Bond. James Bond.";
   String matchHelper[] = { "          ^", "                      ^" };
   Pattern p = Pattern.rupile("Bond");
   Matcher matcher = p.matcher(candidateString);
   // Find the starting point of the first "Bond"
   matcher.find();
   int startIndex = matcher.start();
   System.out.println(candidateString);
   System.out.println(matchHelper[0] + startIndex);
 }

}</source>





REGEX = "\\bdog\\b"

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatcherDemo {

 private static final String REGEX = "\\bdog\\b";
 private static final String INPUT = "dog dog dog doggie dogg";
 public static void main(String[] args) {
   Pattern p = Pattern.rupile(REGEX);
   Matcher m = p.matcher(INPUT); // get a matcher object
   int count = 0;
   while (m.find()) {
     count++;
     System.out.println("Match number " + count);
     System.out.println("start(): " + m.start());
     System.out.println("end(): " + m.end());
   }
 }

}</source>