Java Tutorial/Regular Expressions/Pattern

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

A simple pattern matching demo.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
class RegExpr {
  public static void main(String args[]) {
    Pattern pat;
    Matcher mat;
    boolean found;
    pat = Pattern.rupile("Java");
    mat = pat.matcher("Java");
    found = mat.matches(); 
    if (found)
      System.out.println("Matches");
    else
      System.out.println("No Match");
    mat = pat.matcher("Java 2"); 
    found = mat.matches(); 
    if (found)
      System.out.println("Matches");
    else
      System.out.println("No Match");
  }
}





Control the pattern case

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());
  }
}
/*
*/



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


Pattern.compile method

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 matcher = p.matcher("5");
    boolean isOk = matcher.matches();
    System.out.println("original pattern matches " + isOk);
    // recycle the pattern
    String tmp = p.pattern();
    Pattern p2 = Pattern.rupile(tmp);
    matcher = p.matcher("5");
    isOk = matcher.matches();
    System.out.println("second pattern matches " + isOk);
  }
}





Reuse Pattern Method

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 matcher = p.matcher("5");
    boolean isOk = matcher.matches();
    System.out.println("original pattern matches " + isOk);
    // recycle the pattern
    String tmp = p.pattern();
    Pattern p2 = Pattern.rupile(tmp);
    matcher = p.matcher("5");
    isOk = matcher.matches();
    System.out.println("second pattern matches " + isOk);
  }
}





Split by :

/*
 * 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.Pattern;
public class SplitDemo {
  private static final String REGEX = ":";
  private static final String INPUT = "one:two:three:four:five";
  public static void main(String[] args) {
    Pattern p = Pattern.rupile(REGEX);
    String[] items = p.split(INPUT);
    for (String s : items) {
      System.out.println(s);
    }
  }
}





Split by number

/*
 * 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.Pattern;
public class SplitDemo2 {
  private static final String REGEX = "\\d";
  private static final String INPUT = "one9two4three7four1five";
  public static void main(String[] args) {
    Pattern p = Pattern.rupile(REGEX);
    String[] items = p.split(INPUT);
    for (String s : items) {
      System.out.println(s);
    }
  }
}





Use a character class.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
class RegExpr7 {
  public static void main(String args[]) {
    Pattern pat = Pattern.rupile("[a-z]+");
    Matcher mat = pat.matcher("this is a test.");
    while (mat.find())
      System.out.println("Match: " + mat.group());
  }
}





Use a quantifier.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
class RegExpr4 {
  public static void main(String args[]) {
    Pattern pat = Pattern.rupile("W+");
    Matcher mat = pat.matcher("W WW WWW");
    while (mat.find())
      System.out.println("Match: " + mat.group());
  }
}





Use find() to find a subsequence.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
class RegExpr2 {
  public static void main(String args[]) {
    Pattern pat = Pattern.rupile("Java");
    Matcher mat = pat.matcher("Java 2");
    System.out.println("Looking for Java in Java 2.");
    if (mat.find())
      System.out.println("subsequence found");
    else
      System.out.println("No Match");
  }
}





Use find() to find multiple subsequences.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
class RegExpr3 {
  public static void main(String args[]) {
    Pattern pat = Pattern.rupile("test");
    Matcher mat = pat.matcher("test 1 2 3 test");
    while (mat.find()) {
      System.out.println("test found at index " + mat.start());
    }
  }
}





Use Pattern class to match

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 second sub group (ond)
    int nextIndex = matcher.end(1);
    System.out.println(candidateString);
    System.out.println(matchHelper[3] + nextIndex);
  }
}





Use the ? quantifier.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
class RegExpr6 {
  public static void main(String args[]) {
    Pattern pat = Pattern.rupile("e.+?d");
    Matcher mat = pat.matcher("extend cup end table");
    while (mat.find())
      System.out.println("Match: " + mat.group());
  }
}





Use wildcard and quantifier.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
class RegExpr5 {
  public static void main(String args[]) {
    Pattern pat = Pattern.rupile("e.+d");
    Matcher mat = pat.matcher("extend cup end table");
    while (mat.find())
      System.out.println("Match: " + mat.group());
  }
}