Java/Regular Expressions/Matcher

Материал из Java эксперт
Версия от 18:01, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Another Matcher find and group

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PossesiveExample {
  public static void main(String args[]) {
    String regex = "(\\w++)(\\d\\d)(\\w+)";
    Pattern pattern = Pattern.rupile(regex);
    String candidate = "X99SuperJava";
    Matcher matcher = pattern.matcher(candidate);
    if (matcher.find()) {
      System.out.println("GROUP 0:" + matcher.group(0));
      System.out.println("GROUP 1:" + matcher.group(1));
      System.out.println("GROUP 2:" + matcher.group(2));
      System.out.println("GROUP 3:" + matcher.group(3));
    } else {
      System.out.println("NO MATCHES");
    }
    System.out.println("Done");
  }
}





Another Matcher reset

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherResetCharSequenceExample {
  public static void main(String args[]) {
    test();
  }
  public static void test() {
    String output = "";
    Pattern p = Pattern.rupile("\\d");
    Matcher m1 = p.matcher("01234");
    while (m1.find()) {
      System.out.println("\t\t" + m1.group());
    }
    //now reset the matcher with new data
    m1.reset("56789");
    System.out.println("After resetting the Matcher");
    //iterate through the matcher
    while (m1.find()) {
      System.out.println("\t\t" + m1.group());
    }
  }
}





Check if a text is present at the current position in a buffer for string

   
import java.io.File;
import java.io.FileFilter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *  
 *    http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License. 
 *  
 */

/**
 * Various string manipulation methods that are more efficient then chaining
 * string operations: all is done in the same buffer without creating a bunch of
 * string objects.
 * 
 * @author 
 */
public class Main {
  /**
   * Check if a text is present at the current position in a buffer.
   * 
   * @param byteArray
   *            The buffer which contains the data
   * @param index
   *            Current position in the buffer
   * @param text
   *            The text we want to check
   * @return <code>true</code> if the buffer contains the text.
   */
  public static final int areEquals( byte[] byteArray, int index, String text )
  {
      if ( ( byteArray == null ) || ( byteArray.length == 0 ) || ( byteArray.length <= index ) || ( index < 0 )
          || ( text == null ) )
      {
          return -1;
      }
      else
      {
          try
          {
              byte[] data = text.getBytes( "UTF-8" );
              return areEquals( byteArray, index, data );
          }
          catch ( UnsupportedEncodingException uee )
          {
              return -1;
          }
      }
  }
  /**
   * Check if a text is present at the current position in a buffer.
   * 
   * @param byteArray
   *            The buffer which contains the data
   * @param index
   *            Current position in the buffer
   * @param byteArray2
   *            The text we want to check
   * @return <code>true</code> if the buffer contains the text.
   */
  public static final int areEquals( byte[] byteArray, int index, byte[] byteArray2 )
  {
      if ( ( byteArray == null ) || ( byteArray.length == 0 ) || ( byteArray.length <= index ) || ( index < 0 )
          || ( byteArray2 == null ) || ( byteArray2.length == 0 )
          || ( byteArray2.length > ( byteArray.length + index ) ) )
      {
          return -1;
      }
      else
      {
          for ( int i = 0; i < byteArray2.length; i++ )
          {
              if ( byteArray[index++] != byteArray2[i] )
              {
                  return -1;
              }
          }
          return index;
      }
  }
}





Checks whether a string matches a given wildcard pattern

 
// Copyright (c) 2003-2009, Jodd Team (jodd.org). All Rights Reserved.

/**
 * Checks whether a string matches a given wildcard pattern.
 * Possible patterns allow to match single characters ("?") or any count of
 * characters ("*"). Wildcard characters can be escaped (by an "\").
 * <p>
 * This method uses recursive matching, as in linux or windows. regexp works the same.
 * This method is very fast, comparing to similar implementations.
 */
public class Wildcard {
  /**
   * Checks whether a string matches a given wildcard pattern.
   *
   * @param string  input string
   * @param pattern pattern to match
   * @return      <code>true</code> if string matches the pattern, otherwise <code>false</code>
   */
  public static boolean match(String string, String pattern) {
    return match(string, pattern, 0, 0);
  }
  /**
   * Checks if two strings are equals or if they {@link #match(String, String)}.
   * Useful for cases when matching a lot of equal strings and speed is important.
   */
  public static boolean equalsOrMatch(String string, String pattern) {
    if (string.equals(pattern) == true) {
      return true;
    }
    return match(string, pattern, 0, 0);
  }

  /**
   * Internal matching recursive function.
   */
  private static boolean match(String string, String pattern, int stringStartNdx, int patternStartNdx) {
    int pNdx = patternStartNdx;
    int sNdx = stringStartNdx;
    int pLen = pattern.length();
    if (pLen == 1) {
      if (pattern.charAt(0) == "*") {     // speed-up
        return true;
      }
    }
    int sLen = string.length();
    boolean nextIsNotWildcard = false;
    while (true) {
      // check if end of string and/or pattern occurred
      if ((sNdx >= sLen) == true) {   // end of string still may have pending "*" in pattern
        while ((pNdx < pLen) && (pattern.charAt(pNdx) == "*")) {
          pNdx++;
        }
        return pNdx >= pLen;
      }
      if (pNdx >= pLen) {         // end of pattern, but not end of the string
        return false;
      }
      char p = pattern.charAt(pNdx);    // pattern char
      // perform logic
      if (nextIsNotWildcard == false) {
        if (p == "\\") {
          pNdx++;
          nextIsNotWildcard =  true;
          continue;
        }
        if (p == "?") {
          sNdx++; pNdx++;
          continue;
        }
        if (p == "*") {
          char pnext = 0;           // next pattern char
          if (pNdx + 1 < pLen) {
            pnext = pattern.charAt(pNdx + 1);
          }
          if (pnext == "*") {         // double "*" have the same effect as one "*"
            pNdx++;
            continue;
          }
          int i;
          pNdx++;
          // find recursively if there is any substring from the end of the
          // line that matches the rest of the pattern !!!
          for (i = string.length(); i >= sNdx; i--) {
            if (match(string, pattern, i, pNdx) == true) {
              return true;
            }
          }
          return false;
        }
      } else {
        nextIsNotWildcard = false;
      }
      // check if pattern char and string char are equals
      if (p != string.charAt(sNdx)) {
        return false;
      }
      // everything matches for now, continue
      sNdx++; pNdx++;
    }
  }

  // ---------------------------------------------------------------- utilities
  /**
   * Matches string to at least one pattern.
   * Returns index of matched pattern, or <code>-1</code> otherwise.
   * @see #match(String, String)
   */
  public static int matchOne(String src, String[] patterns) {
    for (int i = 0; i < patterns.length; i++) {
      if (match(src, patterns[i]) == true) {
        return i;
      }
    }
    return -1;
  }
}





Matcher appendReplacement

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherAppendReplacementGroupExample {
  public static void main(String args[]) {
    Pattern p = Pattern.rupile("(James) (Bond)");
    StringBuffer sb = new StringBuffer();
    String candidateString = "My name is Bond. James Bond.";
    String replacement = "$1 Waldo $2";
    Matcher matcher = p.matcher(candidateString);
    matcher.find();
    matcher.appendReplacement(sb, replacement);
    String msg = sb.toString();
    System.out.println(msg);
  }
}





Matcher end

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherEndExample {
  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);
    matcher.find();
    int endIndex = matcher.end();
    System.out.println(candidateString);
    System.out.println(matchHelper[0] + endIndex);
    matcher.find();
    int nextIndex = matcher.end();
    System.out.println(candidateString);
    System.out.println(matchHelper[1] + nextIndex);
  }
}





Matcher end with parameter

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherEndParamExample {
  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);
    matcher.find();
    int endIndex = matcher.end(0);
    System.out.println(candidateString);
    System.out.println(matchHelper[0] + endIndex);
    int nextIndex = matcher.end(1);
    System.out.println(candidateString);
    System.out.println(matchHelper[1] + nextIndex);
    matcher.find();
    endIndex = matcher.end(0);
    System.out.println(candidateString);
    System.out.println(matchHelper[2] + endIndex);
    nextIndex = matcher.end(1);
    System.out.println(candidateString);
    System.out.println(matchHelper[3] + nextIndex);
  }
}





Matcher find

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherFindExample {
  public static void main(String args[]) {
    Pattern p = Pattern.rupile("Java");
    String candidateString = "I love jexp. jexp is about Java.";
    Matcher matcher = p.matcher(candidateString);
    while (matcher.find()) {
      System.out.println(matcher.group());
    }
  }
}





Matcher: Find Demo

  
// : c12:FindDemo.java
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FindDemo {
  public static void main(String[] args) {
    Matcher m = Pattern.rupile("\\w+").matcher(
        "Evening is full of the linnet"s wings");
    while (m.find())
      System.out.println(m.group());
    int i = 0;
    while (m.find(i)) {
      System.out.print(m.group() + " ");
      i++;
    }
  }
} ///:~





Matcher find group

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GreedyExample {
  public static void main(String args[]) {
    String regex = "(\\w+)(\\d\\d)(\\w+)";
    Pattern pattern = Pattern.rupile(regex);
    String candidate = "X99SuperJava";
    Matcher matcher = pattern.matcher(candidate);
    matcher.find();
    System.out.println(matcher.group(1));
    System.out.println(matcher.group(2));
    System.out.println(matcher.group(3));
  }
}





Matcher find with parameter

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherFindParamExample {
  public static void main(String args[]) {
    Pattern p = Pattern.rupile("mice", Pattern.CASE_INSENSITIVE);
    String candidateString = "I hate mice. I really hate MICE.";
    //Attempt to match the candidate String.
    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());
  }
}





Matcher ground count

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NonCapturingGroupExample {
  public static void main(String args[]) {
    String regex = "hello|hi|greetings|(?:good morning)";
    String candidate1 = "jexp say hi to you";
    String candidate2 = "jexp say good morning to you";
    Pattern pattern = Pattern.rupile(regex);
    Matcher matcher = pattern.matcher(candidate1);
    System.out.println("GROUP COUNT:" + matcher.groupCount());
    if (matcher.find())
      System.out.println("GOT 1:" + candidate1);
    matcher.reset();
    matcher = pattern.matcher(candidate2);
    System.out.println("GROUP COUNT:" + matcher.groupCount());
    if (matcher.find())
      System.out.println("GOT 2:" + candidate2);
  }
}





Matcher group

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherGroupExample {
  public static void main(String args[]) {
    test();
  }
  public static void test() {
    Pattern p = Pattern.rupile("Bond");
    String candidateString = "My name is Bond. James Bond.";
    Matcher matcher = p.matcher(candidateString);
    matcher.find();
    System.out.println(matcher.group());
  }
}





Matcher group 2

  

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SimpleGroupExample {
  public static void main(String args[]) {
    Pattern p = Pattern.rupile("\\w\\d");
    String candidate = "J2 is my favorite";
    Matcher matcher = p.matcher(candidate);
    if (matcher.find()) {
      String tmp = matcher.group(0);
      System.out.println(tmp);
    }
  }
}





Matcher group count

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherGroupCountExample {
  public static void main(String args[]) {
    Pattern p = Pattern.rupile("B(ond)");
    String candidateString = "My name is Bond. James Bond.";
    Matcher matcher = p.matcher(candidateString);
    int numberOfGroups = matcher.groupCount();
    System.out.println("numberOfGroups =" + numberOfGroups);
  }
}





Matcher Groups

  
// : c12:Groups.java
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Groups {
  static public final String poem = "Twas brillig, and the slithy toves\n"
      + "Did gyre and gimble in the wabe.\n"
      + "All mimsy were the borogoves,\n"
      + "And the mome raths outgrabe.\n\n"
      + "Beware the Jabberwock, my son,\n"
      + "The jaws that bite, the claws that catch.\n"
      + "Beware the Jubjub bird, and shun\n"
      + "The frumious Bandersnatch.";
  public static void main(String[] args) {
    Matcher m = Pattern.rupile("(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$")
        .matcher(poem);
    while (m.find()) {
      for (int j = 0; j <= m.groupCount(); j++)
        System.out.print("[" + m.group(j) + "]");
      System.out.println();
    }
  }
} ///:~





Matcher group with parameter

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherGroupParamExample {
  public static void main(String args[]) {
    Pattern p = Pattern.rupile("B(ond)");
    String candidateString = "My name is Bond. James Bond.";
    Matcher matcher = p.matcher(candidateString);
    matcher.find();
    String group_0 = matcher.group(0);
    String group_1 = matcher.group(1);
    System.out.println("Group 0 " + group_0);
    System.out.println("Group 1 " + group_1);
    System.out.println(candidateString);
    matcher.find();
    group_0 = matcher.group(0);
    group_1 = matcher.group(1);
    System.out.println("Group 0 " + group_0);
    System.out.println("Group 1 " + group_1);
    System.out.println(candidateString);
  }
}





Matcher group with parameter 2

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SimpleSubGroupExample {
  public static void main(String args[]) {
    Pattern p = Pattern.rupile("\\w(\\d)");
    String candidate = "J9 is my favorite";
    Matcher matcher = p.matcher(candidate);
    if (matcher.find()) {
      String tmp = matcher.group(0);
      System.out.println(tmp);
      tmp = matcher.group(1);
      System.out.println(tmp);
    }
  }
}





Matcher LookingAt

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherLookingAtExample {
  public static void main(String args[]) {
    Pattern p = Pattern.rupile("J2SE");
    String candidateString_1 = "J2SE is the only one for me";
    String candidateString_2 = "For me, it"s J2SE, or nothing at all";
    String candidateString_3 = "J2SEistheonlyoneforme";
    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());
  }
}





Matcher match

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherMatchesExample {
  public static void main(String args[]) {
    Pattern p = Pattern.rupile("J2SE");
    String candidateString_1 = "j2se";
    String candidateString_2 = "J2SE ";
    String candidateString_3 = "J2SE2s";
    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());
  }
}





Matcher Pattern

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





Matcher replaceAll

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherReplaceAllExample {
  public static void main(String args[]) {
    Pattern p = Pattern.rupile("(i|I)ce");
    //create the candidate String
    String candidateString = "I love ice. Ice is my favorite. Ice Ice Ice.";
    Matcher matcher = p.matcher(candidateString);
    String tmp = matcher.replaceAll("Java");
    System.out.println(tmp);
  }
}





Matcher replaceAll 2

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceExample {
  public static void main(String args[]) {
    String regex = "(\\w)(\\d)(\\w+)";
    Pattern pattern = Pattern.rupile(regex);
    String candidate = "X99SuperJava";
    Matcher matcher = pattern.matcher(candidate);
    String tmp = matcher.replaceAll("$33");
    System.out.println("REPLACEMENT: " + tmp);
    System.out.println("ORIGINAL: " + candidate);
  }
}





Matcher replaceFirst

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherReplaceFirstExample {
  public static void main(String args[]) {
    Pattern p = Pattern.rupile("(i|I)ce");
    String candidateString = "I love ice. Ice is my favorite. Ice Ice Ice.";
    Matcher matcher = p.matcher(candidateString);
    String tmp = matcher.replaceFirst("Java");
    System.out.println(tmp);
  }
}





Matcher Reset

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherResetExample {
  public static void main(String args[]) {
    test();
  }
  public static void test() {
    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());
    }
  }
}





Matcher start

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherStartExample {
  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);
    //Find the starting point of the second "Bond"
    matcher.find();
    int nextIndex = matcher.start();
    System.out.println(candidateString);
    System.out.println(matchHelper[1] + nextIndex);
  }
}





Matcher start with parameter

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherStartParamExample {
  public static void main(String args[]) {
    Pattern p = Pattern.rupile("B(ond)");
    String candidateString = "My name is Bond. James Bond.";
    String matchHelper[] = { "          ^", "           ^",
        "                      ^", "                       ^" };
    Matcher matcher = p.matcher(candidateString);
    matcher.find();
    int startIndex = matcher.start(0);
    System.out.println(candidateString);
    System.out.println(matchHelper[0] + startIndex);
    int nextIndex = matcher.start(1);
    System.out.println(candidateString);
    System.out.println(matchHelper[1] + nextIndex);
    matcher.find();
    startIndex = matcher.start(0);
    System.out.println(candidateString);
    System.out.println(matchHelper[2] + startIndex);
    nextIndex = matcher.start(1);
    System.out.println(candidateString);
    System.out.println(matchHelper[3] + nextIndex);
  }
}





Matches Looking

  
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 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:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution 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, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final 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[] argv) {
    // 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());
  }
}





Match Name Formats

  

public class Main {
  public static void main(String args[]) {
    boolean retval = false;
    String name = "first last";
    String nameToken = "\\p{Upper}(\\p{Lower}+\\s?)";
    String namePattern = "(" + nameToken + "){2,3}";
    retval = name.matches(namePattern);
  }
}





Pattern compile

  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReluctantExample {
  public static void main(String args[]) {
    String regex = "(\\d+?)";
    Pattern pattern = Pattern.rupile(regex);
    String candidate = "1234";
    Matcher matcher = pattern.matcher(candidate);
    while (matcher.find()) {
      System.out.println(matcher.group());
    }
    System.out.println("Done");
  }
}





Replace all occurances of the target text with the provided replacement text

 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**********************************************************************************
 *
 * Copyright (c) 2003, 2004 The Regents of the University of Michigan, Trustees of Indiana University,
 *                  Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation
 *
 * Licensed under the Educational Community License Version 1.0 (the "License");
 * By obtaining, using and/or copying this Original Work, you agree that you have read,
 * understand, and will comply with the terms and conditions of the Educational Community License.
 * You may obtain a copy of the License at:
 *
 *      http://cvs.sakaiproject.org/licenses/license_1_0.html
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 **********************************************************************************/
public class Utils {
  /**
   * Replace all occurances of the target text with the provided replacement
   * text. Both target and replacement may be regular expressions - see
   * <code>java.util.regex.Matcher</code>.
   * 
   * @param text
   *          Text to modify
   * @param targetText
   *          Text to find and replace
   * @param newText
   *          New text
   * @return Updated text
   */
  public static String replace(String text, String targetText, String newText) {
    Pattern pattern = Pattern.rupile(targetText, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(text);
    return matcher.replaceAll(newText);
  }
}





Show line ending matching using Regular Expressions class

  
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */

import java.util.regex.Pattern;
/**
 * Show line ending matching using RE class.
 * 
 * @author Ian F. Darwin, http://www.darwinsys.ru/
 * @version $Id: NLMatch.java,v 1.6 2004/02/09 03:33:42 ian Exp $
 */
public class NLMatch {
  public static void main(String[] argv) {
    String input = "I dream of engines\nmore engines, all day long";
    System.out.println("INPUT: " + input);
    System.out.println();
    String[] patt = { "engines.more engines", "engines$" };
    for (int i = 0; i < patt.length; i++) {
      System.out.println("PATTERN " + patt[i]);
      boolean found;
      Pattern p1l = Pattern.rupile(patt[i]);
      found = p1l.matcher(input).find();
      System.out.println("DEFAULT match " + found);
      Pattern pml = Pattern.rupile(patt[i], Pattern.DOTALL
          | Pattern.MULTILINE);
      found = pml.matcher(input).find();
      System.out.println("MultiLine match " + found);
      System.out.println();
    }
  }
}