Java/Regular Expressions/Matcher
Содержание
- 1 Another Matcher find and group
- 2 Another Matcher reset
- 3 Check if a text is present at the current position in a buffer for string
- 4 Checks whether a string matches a given wildcard pattern
- 5 Matcher appendReplacement
- 6 Matcher end
- 7 Matcher end with parameter
- 8 Matcher find
- 9 Matcher: Find Demo
- 10 Matcher find group
- 11 Matcher find with parameter
- 12 Matcher ground count
- 13 Matcher group
- 14 Matcher group 2
- 15 Matcher group count
- 16 Matcher Groups
- 17 Matcher group with parameter
- 18 Matcher group with parameter 2
- 19 Matcher LookingAt
- 20 Matcher match
- 21 Matcher Pattern
- 22 Matcher replaceAll
- 23 Matcher replaceAll 2
- 24 Matcher replaceFirst
- 25 Matcher Reset
- 26 Matcher start
- 27 Matcher start with parameter
- 28 Matches Looking
- 29 Match Name Formats
- 30 Pattern compile
- 31 Replace all occurances of the target text with the provided replacement text
- 32 Show line ending matching using Regular Expressions class
Another Matcher find and group
<source lang="java">
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"); }
}
</source>
Another Matcher reset
<source lang="java">
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()); } }
}
</source>
Check if a text is present at the current position in a buffer for string
<source lang="java">
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 * @returntrue
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 * @returntrue
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; } }
}
</source>
Checks whether a string matches a given wildcard pattern
<source lang="java">
// 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 "\").*
* 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 true
if string matches the pattern, otherwise false
*/
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 -1
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;
}
}
</source>
Matcher appendReplacement
<source lang="java">
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); }
}
</source>
Matcher end
<source lang="java">
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); }
}
</source>
Matcher end with parameter
<source lang="java">
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); }
}
</source>
Matcher find
<source lang="java">
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()); } }
}
</source>
Matcher: Find Demo
<source lang="java">
// : 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++; } }
} ///:~
</source>
Matcher find group
<source lang="java">
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)); }
}
</source>
Matcher find with parameter
<source lang="java">
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()); }
}
</source>
Matcher ground count
<source lang="java">
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); }
}
</source>
Matcher group
<source lang="java">
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()); }
}
</source>
Matcher group 2
<source lang="java">
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); } }
}
</source>
Matcher group count
<source lang="java">
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); }
}
</source>
Matcher Groups
<source lang="java">
// : 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(); } }
} ///:~
</source>
Matcher group with parameter
<source lang="java">
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); }
}
</source>
Matcher group with parameter 2
<source lang="java">
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); } }
}
</source>
Matcher LookingAt
<source lang="java">
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()); }
}
</source>
Matcher match
<source lang="java">
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()); }
}
</source>
Matcher Pattern
<source lang="java">
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()); }
}
</source>
Matcher replaceAll
<source lang="java">
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); }
}
</source>
Matcher replaceAll 2
<source lang="java">
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); }
}
</source>
Matcher replaceFirst
<source lang="java">
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); }
}
</source>
Matcher Reset
<source lang="java">
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()); } }
}
</source>
Matcher start
<source lang="java">
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); }
}
</source>
Matcher start with parameter
<source lang="java">
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); }
}
</source>
Matches Looking
<source lang="java">
/* 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()); }
}
</source>
Match Name Formats
<source lang="java">
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); }
}
</source>
Pattern compile
<source lang="java">
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"); }
}
</source>
Replace all occurances of the target text with the provided replacement text
<source lang="java">
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
* java.util.regex.Matcher
.
*
* @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);
}
}
</source>
Show line ending matching using Regular Expressions class
<source lang="java">
/*
* 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(); } }
}
</source>