Java/Regular Expressions/Pattern
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 A block of text to use as input to the regular expression matcher
- 2 Adding Comments to a Regular Expression
- 3 Allows you to easily try out regular expressions
- 4 Another pattern split
- 5 Compiling a Pattern with Multiple Flags
- 6 Find all matches
- 7 Finding Every Occurrence of the Letter A
- 8 Find the end point of the second "test"
- 9 Implement a pattern matcher for regular expressions
- 10 Match Duplicate Words
- 11 Matcher.end(): find the end point
- 12 Matcher.reset(CharSequence)
- 13 Matcher.reset: restart
- 14 Matcher.start(): Find the starting point
- 15 Matcher.start(int) Example
- 16 Matching Across Line Boundaries in a Regular Expression
- 17 Match one or more
- 18 PatternConvenience -- demonstrate java.util.regex.Pattern convenience routine
- 19 Pattern: flags
- 20 Pattern helper
- 21 Pattern Match
- 22 Pattern: Resetting
- 23 Pattern Split
- 24 Possessive Qualifier Example
- 25 Reg Exp Example
- 26 Regular expression and CharSequence
- 27 Regular expression search program
- 28 Regular expressions: start End
- 29 Setting Case Sensitivity in a Regular Expression
- 30 Show use of Pattern.CANON_EQ
- 31 Simple example of using Regular Expressions functionality in String class
- 32 Simple Negative Lookahead
- 33 Simple Pattern
- 34 Simple Positive Lookahead
- 35 Simple Positive Lookbehind
- 36 Tabs and newlines in the pattern are ignored as well
- 37 The inline modifier can also contain pattern characters using the form (?x:abc)
- 38 Use a character set
- 39 Use an inline modifier: a (?x: b)
- 40 Use an inline modifier: (?x)a [\\ ] b
- 41 Use an inline modifier: x)a \\s b
- 42 Use enclosing form
- 43 Using the find(int) Method
- 44 Using the find() Method from Matcher
- 45 Using the lookingAt Method
- 46 Validation Test With Pattern And Matcher
A block of text to use as input to the regular expression matcher
// : c12:TheReplacements.java
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
* ! Here"s a block of text to use as input to the regular expression matcher.
* Note that we"ll first extract the block of text by looking for the special
* delimiters, then process the extracted block. !
*/
public class TheReplacements {
public static void main(String[] args) throws Exception {
String s = TextFile.read("TheReplacements.java");
// Match the specially-commented block of text above:
Matcher mInput = Pattern.rupile("/\\*!(.*)!\\*/", Pattern.DOTALL)
.matcher(s);
if (mInput.find())
s = mInput.group(1); // Captured by parentheses
// Replace two or more spaces with a single space:
s = s.replaceAll(" {2,}", " ");
// Replace one or more spaces at the beginning of each
// line with no spaces. Must enable MULTILINE mode:
s = s.replaceAll("(?m)^ +", "");
System.out.println(s);
s = s.replaceFirst("[aeiou]", "(VOWEL1)");
StringBuffer sbuf = new StringBuffer();
Pattern p = Pattern.rupile("[aeiou]");
Matcher m = p.matcher(s);
// Process the find information as you
// perform the replacements:
while (m.find())
m.appendReplacement(sbuf, m.group().toUpperCase());
// Put in the remainder of the text:
m.appendTail(sbuf);
System.out.println(sbuf);
}
} ///:~
class TextFile extends ArrayList {
// Tools to read and write files as single strings:
public static String read(String fileName) throws IOException {
StringBuffer sb = new StringBuffer();
BufferedReader in = new BufferedReader(new FileReader(fileName));
String s;
while ((s = in.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
in.close();
return sb.toString();
}
public static void write(String fileName, String text) throws IOException {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(
fileName)));
out.print(text);
out.close();
}
public TextFile(String fileName) throws IOException {
super(Arrays.asList(read(fileName).split("\n")));
}
public void write(String fileName) throws IOException {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(
fileName)));
for (int i = 0; i < size(); i++)
out.println(get(i));
out.close();
}
// Simple test:
public static void main(String[] args) throws Exception {
String file = read("TextFile.java");
write("test.txt", file);
TextFile text = new TextFile("test.txt");
text.write("test2.txt");
}
} ///:~
Adding Comments to a Regular Expression
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] argv) throws Exception {
// Use COMMENTS but include a character class with a space
CharSequence inputStr = "a b";
String patternStr = "a b";
// Compile without comments
Pattern pattern = Pattern.rupile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.matches();
// Compile with comments
pattern = Pattern.rupile(patternStr, Pattern.ruMENTS);
matcher = pattern.matcher(inputStr);
matchFound = matcher.matches();
patternStr = "a [\\ ] b";
pattern = Pattern.rupile(patternStr, Pattern.ruMENTS);
matcher = pattern.matcher(inputStr);
matchFound = matcher.matches();
}
}
Allows you to easily try out regular expressions
// : c12:TestRegularExpression.java
// Allows you to easly try out regular expressions.
// {Args: abcabcabcdefabc "abc+" "(abc)+" "(abc){2,}" }
// 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 TestRegularExpression {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Usage:\n" + "java TestRegularExpression "
+ "characterSequence regularExpression+");
System.exit(0);
}
System.out.println("Input: \"" + args[0] + "\"");
for (int i = 1; i < args.length; i++) {
System.out.println("Regular expression: \"" + args[i] + "\"");
Pattern p = Pattern.rupile(args[i]);
Matcher m = p.matcher(args[0]);
while (m.find()) {
System.out.println("Match \"" + m.group() + "\" at positions "
+ m.start() + "-" + (m.end() - 1));
}
}
}
} ///:~
Another pattern split
import java.util.regex.Pattern;
public class PatternSplit {
public static void main(String args[]) {
String statement = "I will not compromise. I will not "
+ "cooperate. There will be no concession, no conciliation, no "
+ "finding the middle ground, and no give and take.";
String tokens[] = null;
String splitPattern = "compromise|cooperate|concession|"
+ "conciliation|(finding the middle ground)|(give and take)";
Pattern p = Pattern.rupile(splitPattern);
tokens = p.split(statement);
System.out.println("REGEX PATTERN:\n" + splitPattern + "\n");
System.out.println("STATEMENT:\n" + statement + "\n");
System.out.println("TOKENS:");
for (int i = 0; i < tokens.length; i++) {
System.out.println(tokens[i]);
}
}
}
Compiling a Pattern with Multiple Flags
Multiple flags must be combined using the or operator (|).
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] argv) throws Exception {
CharSequence inputStr = "Abc\ndef";
String patternStr = "abc$";
// Compile with multiline and case-insensitive enabled
Pattern pattern = Pattern.rupile(patternStr, Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.find();
}
}
Find all matches
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] argv) throws Exception {
Pattern pattern = Pattern.rupile("pattern");
Matcher matcher = pattern.matcher("infile.txt");
// Find all matches
while (matcher.find()) {
// Get the matching string
String match = matcher.group();
}
}
}
Finding Every Occurrence of the Letter A
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) throws Exception {
String candidate = "this is a test, A TEST.";
String regex = "\\ba\\w*\\b";
Pattern p = Pattern.rupile(regex);
Matcher m = p.matcher(candidate);
String val = null;
System.out.println("INPUT: " + candidate);
System.out.println("REGEX: " + regex + "\r\n");
while (m.find()) {
val = m.group();
System.out.println("MATCH: " + val);
}
if (val == null) {
System.out.println("NO MATCHES: ");
}
}
}
Find the end point of the second "test"
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
String candidateString = "This is a test. This is another test.";
Pattern p = Pattern.rupile("test");
Matcher matcher = p.matcher(candidateString);
matcher.find();
int nextIndex = matcher.end();
System.out.println(nextIndex);
}
}
Implement a pattern matcher for regular expressions
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.text.DefaultFormatter;
public class Main extends DefaultFormatter {
protected Matcher matcher;
public Main(Pattern regex) {
setOverwriteMode(false);
matcher = regex.matcher("");
}
public Object stringToValue(String string) throws java.text.ParseException {
if (string == null) return null;
matcher.reset(string);
if (! matcher.matches())
throw new java.text.ParseException("does not match regex", 0);
return super.stringToValue(string);
}
public static void main(String argv[]) {
Pattern evenLength = Pattern.rupile("(..)*");
JFormattedTextField ftf1 = new JFormattedTextField(new Main(evenLength));
JLabel lab2 = new JLabel("no vowels:");
Pattern noVowels = Pattern.rupile("[^aeiou]*",Pattern.CASE_INSENSITIVE);
Main noVowelFormatter = new Main(noVowels);
noVowelFormatter.setAllowsInvalid(false);
JFormattedTextField ftf2 = new JFormattedTextField(noVowelFormatter);
}
}
Match Duplicate Words
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) throws Exception {
String duplicatePattern = "\\b(\\w+) \\1\\b";
Pattern p = Pattern.rupile(duplicatePattern);
int matches = 0;
String phrase = "this is a test";
Matcher m = p.matcher(phrase);
String val = null;
while (m.find()) {
val = ":" + m.group() + ":";
System.out.println(val);
matches++;
}
}
}
Matcher.end(): find the end point
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
String candidateString = "This is a test. This is another test.";
Pattern p = Pattern.rupile("test");
Matcher matcher = p.matcher(candidateString);
matcher.find();
int endIndex = matcher.end();
System.out.println(candidateString);
System.out.println( endIndex);
}
}
Matcher.reset(CharSequence)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
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("56789");
while (m1.find()) {
System.out.println("\t\t" + m1.group());
}
}
}
Matcher.reset: restart
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
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());
}
}
}
Matcher.start(): Find the starting point
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
String candidateString = "This is a test. This is another test";
Pattern p = Pattern.rupile("test");
Matcher matcher = p.matcher(candidateString);
// Find the starting point of the first "test"
matcher.find();
int startIndex = matcher.start();
System.out.println(candidateString);
System.out.println(startIndex);
// Find the starting point of the second "test"
matcher.find();
int nextIndex = matcher.start();
System.out.println(candidateString);
System.out.println(nextIndex);
}
}
Matcher.start(int) Example
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
Pattern p = Pattern.rupile("t(est)");
String candidateString = "This is a test. This is another test";
Matcher matcher = p.matcher(candidateString);
matcher.find();
int startIndex = matcher.start(0);
System.out.println(candidateString);
System.out.println(startIndex);
}
}
Matching Across Line Boundaries in a Regular Expression
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] argv) throws Exception {
CharSequence inputStr = "abc\ndef";
String patternStr = ".*c.+d.*";
Pattern pattern = Pattern.rupile(patternStr, Pattern.DOTALL);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.matches();
matchFound = pattern.matches(".*c.+d.*", "abc\r\ndef");
matchFound = pattern.matches("(?s).*c.+d.*", "abc\r\ndef");
}
}
Match one or more
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
String regex = "ad*";
String input = "add";
boolean isMatch = Pattern.matches(regex, input);
System.out.println(isMatch);// return true
}
}
PatternConvenience -- demonstrate java.util.regex.Pattern convenience routine
/*
* 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.*;
/**
* PatternConvenience -- demonstrate java.util.regex.Pattern convenience routine
* @author Ian F. Darwin
* @version $Id: PatternConvenience.java,v 1.1 2003/05/09 19:25:50 ian Exp $
*/
public class PatternConvenience {
public static void main(String[] argv) {
String pattern = ".*Q[^u]\\d+\\..*";
String line = "Order QT300. Now!";
if (Pattern.matches(pattern, line)) {
System.out.println(line + " matches \"" + pattern + "\"");
} else {
System.out.println("NO MATCH");
}
}
}
Pattern: flags
// : c12:ReFlags.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 ReFlags {
public static void main(String[] args) {
Pattern p = Pattern.rupile("^java", Pattern.CASE_INSENSITIVE
| Pattern.MULTILINE);
Matcher m = p.matcher("java has regex\nJava has regex\n"
+ "JAVA has pretty good regular expressions\n"
+ "Regular expressions are in Java");
while (m.find())
System.out.println(m.group());
}
} ///:~
Pattern helper
/*
* Static String formatting and query routines.
* Copyright (C) 2001-2005 Stephen Ostermiller
* http://ostermiller.org/contact.pl?regarding=Java+Utilities
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* See COPYING.TXT for details.
*/
import java.util.HashMap;
import java.util.regex.Pattern;
/**
* Utilities for String formatting, manipulation, and queries.
* More information about this class is available from .
*
* @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities
* @since ostermillerutils 1.00.00
*/
public class StringHelper {
/**
* Build a regular expression that is each of the terms or"d together.
*
* @param terms a list of search terms.
* @param sb place to build the regular expression.
* @throws IllegalArgumentException if the length of terms is zero.
*
* @since ostermillerutils 1.02.25
*/
private static void buildFindAnyPattern(String[] terms, StringBuffer sb){
if (terms.length == 0) throw new IllegalArgumentException("There must be at least one term to find.");
sb.append("(?:");
for (int i=0; i<terms.length; i++){
if (i>0) sb.append("|");
sb.append("(?:");
sb.append(escapeRegularExpressionLiteral(terms[i]));
sb.append(")");
}
sb.append(")");
}
/**
* Compile a pattern that can will match a string if the string
* contains any of the given terms.
* <p>
* Usage:<br>
* <code>boolean b = getContainsAnyPattern(terms).matcher(s).matches();</code>
* <p>
* If multiple strings are matched against the same set of terms,
* it is more efficient to reuse the pattern returned by this function.
*
* @param terms Array of search strings.
* @return Compiled pattern that can be used to match a string to see if it contains any of the terms.
*
* @since ostermillerutils 1.02.25
*/
public static Pattern getContainsAnyPattern(String[] terms){
StringBuffer sb = new StringBuffer();
sb.append("(?s).*");
buildFindAnyPattern(terms, sb);
sb.append(".*");
return Pattern.rupile(sb.toString());
}
/**
* Compile a pattern that can will match a string if the string
* equals any of the given terms.
* <p>
* Usage:<br>
* <code>boolean b = getEqualsAnyPattern(terms).matcher(s).matches();</code>
* <p>
* If multiple strings are matched against the same set of terms,
* it is more efficient to reuse the pattern returned by this function.
*
* @param terms Array of search strings.
* @return Compiled pattern that can be used to match a string to see if it equals any of the terms.
*
* @since ostermillerutils 1.02.25
*/
public static Pattern getEqualsAnyPattern(String[] terms){
StringBuffer sb = new StringBuffer();
sb.append("(?s)\\A");
buildFindAnyPattern(terms, sb);
sb.append("\\z");
return Pattern.rupile(sb.toString());
}
/**
* Compile a pattern that can will match a string if the string
* starts with any of the given terms.
* <p>
* Usage:<br>
* <code>boolean b = getStartsWithAnyPattern(terms).matcher(s).matches();</code>
* <p>
* If multiple strings are matched against the same set of terms,
* it is more efficient to reuse the pattern returned by this function.
*
* @param terms Array of search strings.
* @return Compiled pattern that can be used to match a string to see if it starts with any of the terms.
*
* @since ostermillerutils 1.02.25
*/
public static Pattern getStartsWithAnyPattern(String[] terms){
StringBuffer sb = new StringBuffer();
sb.append("(?s)\\A");
buildFindAnyPattern(terms, sb);
sb.append(".*");
return Pattern.rupile(sb.toString());
}
/**
* Compile a pattern that can will match a string if the string
* ends with any of the given terms.
* <p>
* Usage:<br>
* <code>boolean b = getEndsWithAnyPattern(terms).matcher(s).matches();</code>
* <p>
* If multiple strings are matched against the same set of terms,
* it is more efficient to reuse the pattern returned by this function.
*
* @param terms Array of search strings.
* @return Compiled pattern that can be used to match a string to see if it ends with any of the terms.
*
* @since ostermillerutils 1.02.25
*/
public static Pattern getEndsWithAnyPattern(String[] terms){
StringBuffer sb = new StringBuffer();
sb.append("(?s).*");
buildFindAnyPattern(terms, sb);
sb.append("\\z");
return Pattern.rupile(sb.toString());
}
/**
* Compile a pattern that can will match a string if the string
* contains any of the given terms.
* <p>
* Case is ignored when matching using Unicode case rules.
* <p>
* Usage:<br>
* <code>boolean b = getContainsAnyPattern(terms).matcher(s).matches();</code>
* <p>
* If multiple strings are matched against the same set of terms,
* it is more efficient to reuse the pattern returned by this function.
*
* @param terms Array of search strings.
* @return Compiled pattern that can be used to match a string to see if it contains any of the terms.
*
* @since ostermillerutils 1.02.25
*/
public static Pattern getContainsAnyIgnoreCasePattern(String[] terms){
StringBuffer sb = new StringBuffer();
sb.append("(?i)(?u)(?s).*");
buildFindAnyPattern(terms, sb);
sb.append(".*");
return Pattern.rupile(sb.toString());
}
/**
* Compile a pattern that can will match a string if the string
* equals any of the given terms.
* <p>
* Case is ignored when matching using Unicode case rules.
* <p>
* Usage:<br>
* <code>boolean b = getEqualsAnyPattern(terms).matcher(s).matches();</code>
* <p>
* If multiple strings are matched against the same set of terms,
* it is more efficient to reuse the pattern returned by this function.
*
* @param terms Array of search strings.
* @return Compiled pattern that can be used to match a string to see if it equals any of the terms.
*
* @since ostermillerutils 1.02.25
*/
public static Pattern getEqualsAnyIgnoreCasePattern(String[] terms){
StringBuffer sb = new StringBuffer();
sb.append("(?i)(?u)(?s)\\A");
buildFindAnyPattern(terms, sb);
sb.append("\\z");
return Pattern.rupile(sb.toString());
}
/**
* Compile a pattern that can will match a string if the string
* starts with any of the given terms.
* <p>
* Case is ignored when matching using Unicode case rules.
* <p>
* Usage:<br>
* <code>boolean b = getStartsWithAnyPattern(terms).matcher(s).matches();</code>
* <p>
* If multiple strings are matched against the same set of terms,
* it is more efficient to reuse the pattern returned by this function.
*
* @param terms Array of search strings.
* @return Compiled pattern that can be used to match a string to see if it starts with any of the terms.
*
* @since ostermillerutils 1.02.25
*/
public static Pattern getStartsWithAnyIgnoreCasePattern(String[] terms){
StringBuffer sb = new StringBuffer();
sb.append("(?i)(?u)(?s)\\A");
buildFindAnyPattern(terms, sb);
sb.append(".*");
return Pattern.rupile(sb.toString());
}
/**
* Compile a pattern that can will match a string if the string
* ends with any of the given terms.
* <p>
* Case is ignored when matching using Unicode case rules.
* <p>
* Usage:<br>
* <code>boolean b = getEndsWithAnyPattern(terms).matcher(s).matches();</code>
* <p>
* If multiple strings are matched against the same set of terms,
* it is more efficient to reuse the pattern returned by this function.
*
* @param terms Array of search strings.
* @return Compiled pattern that can be used to match a string to see if it ends with any of the terms.
*
* @since ostermillerutils 1.02.25
*/
public static Pattern getEndsWithAnyIgnoreCasePattern(String[] terms){
StringBuffer sb = new StringBuffer();
sb.append("(?i)(?u)(?s).*");
buildFindAnyPattern(terms, sb);
sb.append("\\z");
return Pattern.rupile(sb.toString());
}
/**
* Tests to see if the given string contains any of the given terms.
* <p>
* This implementation is more efficient than the brute force approach
* of testing the string against each of the terms. It instead compiles
* a single regular expression that can test all the terms at once, and
* uses that expression against the string.
* <p>
* This is a convenience method. If multiple strings are tested against
* the same set of terms, it is more efficient not to compile the regular
* expression multiple times.
* @see #getContainsAnyPattern(String[])
*
* @param s String that may contain any of the given terms.
* @param terms list of substrings that may be contained in the given string.
* @return true iff one of the terms is a substring of the given string.
*
* @since ostermillerutils 1.02.25
*/
public static boolean containsAny(String s, String[] terms){
return getContainsAnyPattern(terms).matcher(s).matches();
}
/**
* Tests to see if the given string equals any of the given terms.
* <p>
* This implementation is more efficient than the brute force approach
* of testing the string against each of the terms. It instead compiles
* a single regular expression that can test all the terms at once, and
* uses that expression against the string.
* <p>
* This is a convenience method. If multiple strings are tested against
* the same set of terms, it is more efficient not to compile the regular
* expression multiple times.
* @see #getEqualsAnyPattern(String[])
*
* @param s String that may equal any of the given terms.
* @param terms list of strings that may equal the given string.
* @return true iff one of the terms is equal to the given string.
*
* @since ostermillerutils 1.02.25
*/
public static boolean equalsAny(String s, String[] terms){
return getEqualsAnyPattern(terms).matcher(s).matches();
}
/**
* Tests to see if the given string starts with any of the given terms.
* <p>
* This implementation is more efficient than the brute force approach
* of testing the string against each of the terms. It instead compiles
* a single regular expression that can test all the terms at once, and
* uses that expression against the string.
* <p>
* This is a convenience method. If multiple strings are tested against
* the same set of terms, it is more efficient not to compile the regular
* expression multiple times.
* @see #getStartsWithAnyPattern(String[])
*
* @param s String that may start with any of the given terms.
* @param terms list of strings that may start with the given string.
* @return true iff the given string starts with one of the given terms.
*
* @since ostermillerutils 1.02.25
*/
public static boolean startsWithAny(String s, String[] terms){
return getStartsWithAnyPattern(terms).matcher(s).matches();
}
/**
* Tests to see if the given string ends with any of the given terms.
* <p>
* This implementation is more efficient than the brute force approach
* of testing the string against each of the terms. It instead compiles
* a single regular expression that can test all the terms at once, and
* uses that expression against the string.
* <p>
* This is a convenience method. If multiple strings are tested against
* the same set of terms, it is more efficient not to compile the regular
* expression multiple times.
* @see #getEndsWithAnyPattern(String[])
*
* @param s String that may end with any of the given terms.
* @param terms list of strings that may end with the given string.
* @return true iff the given string ends with one of the given terms.
*
* @since ostermillerutils 1.02.25
*/
public static boolean endsWithAny(String s, String[] terms){
return getEndsWithAnyPattern(terms).matcher(s).matches();
}
/**
* Tests to see if the given string contains any of the given terms.
* <p>
* Case is ignored when matching using Unicode case rules.
* <p>
* This implementation is more efficient than the brute force approach
* of testing the string against each of the terms. It instead compiles
* a single regular expression that can test all the terms at once, and
* uses that expression against the string.
* <p>
* This is a convenience method. If multiple strings are tested against
* the same set of terms, it is more efficient not to compile the regular
* expression multiple times.
* @see #getContainsAnyIgnoreCasePattern(String[])
*
* @param s String that may contain any of the given terms.
* @param terms list of substrings that may be contained in the given string.
* @return true iff one of the terms is a substring of the given string.
*
* @since ostermillerutils 1.02.25
*/
public static boolean containsAnyIgnoreCase(String s, String[] terms){
return getContainsAnyIgnoreCasePattern(terms).matcher(s).matches();
}
/**
* Tests to see if the given string equals any of the given terms.
* <p>
* Case is ignored when matching using Unicode case rules.
* <p>
* This implementation is more efficient than the brute force approach
* of testing the string against each of the terms. It instead compiles
* a single regular expression that can test all the terms at once, and
* uses that expression against the string.
* <p>
* This is a convenience method. If multiple strings are tested against
* the same set of terms, it is more efficient not to compile the regular
* expression multiple times.
* @see #getEqualsAnyIgnoreCasePattern(String[])
*
* @param s String that may equal any of the given terms.
* @param terms list of strings that may equal the given string.
* @return true iff one of the terms is equal to the given string.
*
* @since ostermillerutils 1.02.25
*/
public static boolean equalsAnyIgnoreCase(String s, String[] terms){
return getEqualsAnyIgnoreCasePattern(terms).matcher(s).matches();
}
/**
* Tests to see if the given string starts with any of the given terms.
* <p>
* Case is ignored when matching using Unicode case rules.
* <p>
* This implementation is more efficient than the brute force approach
* of testing the string against each of the terms. It instead compiles
* a single regular expression that can test all the terms at once, and
* uses that expression against the string.
* <p>
* This is a convenience method. If multiple strings are tested against
* the same set of terms, it is more efficient not to compile the regular
* expression multiple times.
* @see #getStartsWithAnyIgnoreCasePattern(String[])
*
* @param s String that may start with any of the given terms.
* @param terms list of strings that may start with the given string.
* @return true iff the given string starts with one of the given terms.
*
* @since ostermillerutils 1.02.25
*/
public static boolean startsWithAnyIgnoreCase(String s, String[] terms){
return getStartsWithAnyIgnoreCasePattern(terms).matcher(s).matches();
}
/**
* Tests to see if the given string ends with any of the given terms.
* <p>
* Case is ignored when matching using Unicode case rules.
* <p>
* This implementation is more efficient than the brute force approach
* of testing the string against each of the terms. It instead compiles
* a single regular expression that can test all the terms at once, and
* uses that expression against the string.
* <p>
* This is a convenience method. If multiple strings are tested against
* the same set of terms, it is more efficient not to compile the regular
* expression multiple times.
* @see #getEndsWithAnyIgnoreCasePattern(String[])
*
* @param s String that may end with any of the given terms.
* @param terms list of strings that may end with the given string.
* @return true iff the given string ends with one of the given terms.
*
* @since ostermillerutils 1.02.25
*/
public static boolean endsWithAnyIgnoreCase(String s, String[] terms){
return getEndsWithAnyIgnoreCasePattern(terms).matcher(s).matches();
}
/**
* Escapes characters that have special meaning to
* regular expressions
*
* @param s String to be escaped
* @return escaped String
* @throws NullPointerException if s is null.
*
* @since ostermillerutils 1.02.25
*/
public static String escapeRegularExpressionLiteral(String s){
// According to the documentation in the Pattern class:
//
// The backslash character ("\") serves to introduce escaped constructs,
// as defined in the table above, as well as to quote characters that
// otherwise would be interpreted as unescaped constructs. Thus the
// expression \\ matches a single backslash and \{ matches a left brace.
//
// It is an error to use a backslash prior to any alphabetic character
// that does not denote an escaped construct; these are reserved for future
// extensions to the regular-expression language. A backslash may be used
// prior to a non-alphabetic character regardless of whether that character
// is part of an unescaped construct.
//
// As a result, escape everything except [0-9a-zA-Z]
int length = s.length();
int newLength = length;
// first check for characters that might
// be dangerous and calculate a length
// of the string that has escapes.
for (int i=0; i<length; i++){
char c = s.charAt(i);
if (!((c>="0" && c<="9") || (c>="A" && c<="Z") || (c>="a" && c<="z"))){
newLength += 1;
}
}
if (length == newLength){
// nothing to escape in the string
return s;
}
StringBuffer sb = new StringBuffer(newLength);
for (int i=0; i<length; i++){
char c = s.charAt(i);
if (!((c>="0" && c<="9") || (c>="A" && c<="Z") || (c>="a" && c<="z"))){
sb.append("\\");
}
sb.append(c);
}
return sb.toString();
}
}
Pattern Match
import java.util.regex.Pattern;
public class PatternMatchesTest {
public static void main(String args[]) {
String regex = "ad*";
String input = "add";
boolean isMatch = Pattern.matches(regex, input);
System.out.println(isMatch);//return true
}
}
Pattern: Resetting
// : c12:Resetting.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 Resetting {
public static void main(String[] args) throws Exception {
Matcher m = Pattern.rupile("[frb][aiu][gx]").matcher(
"fix the rug with bags");
while (m.find())
System.out.println(m.group());
m.reset("fix the rig with rags");
while (m.find())
System.out.println(m.group());
}
} ///:~
Pattern Split
import java.util.regex.Pattern;
public class PatternSplitExample {
public static void main(String args[]) {
Pattern p = Pattern.rupile(" ");
String tmp = "this is the String I want to split up";
String[] tokens = p.split(tmp);
for (int i = 0; i < tokens.length; i++) {
System.out.println(tokens[i]);
}
}
}
Possessive Qualifier Example
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
String regex = "(\\w++)(\\d\\d)(\\w+)";
Pattern pattern = Pattern.rupile(regex);
String candidate = "X99 test 55";
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");
}
}
}
Reg Exp Example
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExpExample {
public static void main(String args[]) {
String fileName = "RETestSource.java";
String unadornedClassRE = "^\\s*class (\\w+)";
String doubleIdentifierRE = "\\b(\\w+)\\s+\\1\\b";
Pattern classPattern = Pattern.rupile(unadornedClassRE);
Pattern doublePattern = Pattern.rupile(doubleIdentifierRE);
Matcher classMatcher, doubleMatcher;
int lineNumber = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line;
while ((line = br.readLine()) != null) {
lineNumber++;
classMatcher = classPattern.matcher(line);
doubleMatcher = doublePattern.matcher(line);
if (classMatcher.find()) {
System.out.println("The class [" + classMatcher.group(1)
+ "] is not public");
}
while (doubleMatcher.find()) {
System.out.println("The word \"" + doubleMatcher.group(1)
+ "\" occurs twice at position "
+ doubleMatcher.start() + " on line " + lineNumber);
}
}
} catch (IOException ioe) {
System.out.println("IOException: " + ioe);
ioe.printStackTrace();
}
}
}
Regular expression and CharSequence
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String patternStr = "b";
Pattern pattern = Pattern.rupile(patternStr);
CharSequence inputStr = "a b c b";
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.find();
System.out.println(matchFound);
String match = matcher.group();
System.out.println(match);
int start = matcher.start();
int end = matcher.end();
System.out.println(start);
System.out.println(end);
matchFound = matcher.find();
}
}
Regular expression search program
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String patternStr = "b";
Pattern pattern = Pattern.rupile(patternStr);
CharSequence inputStr = "a b c b";
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.find();
System.out.println(matchFound);
String match = matcher.group();
int start = matcher.start();
int end = matcher.end();
System.out.println(start);
System.out.println(end);
matchFound = matcher.find();
}
}
Regular expressions: start End
// : c12:StartEnd.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 StartEnd {
public static void main(String[] args) {
String[] input = new String[] { "Java has regular expressions in 1.4",
"regular expressions now expressing in Java",
"Java represses oracular expressions" };
Pattern p1 = Pattern.rupile("re\\w*"), p2 = Pattern.rupile("Java.*");
for (int i = 0; i < input.length; i++) {
System.out.println("input " + i + ": " + input[i]);
Matcher m1 = p1.matcher(input[i]), m2 = p2.matcher(input[i]);
while (m1.find())
System.out.println("m1.find() "" + m1.group() + "" start = "
+ m1.start() + " end = " + m1.end());
while (m2.find())
System.out.println("m2.find() "" + m2.group() + "" start = "
+ m2.start() + " end = " + m2.end());
if (m1.lookingAt()) // No reset() necessary
System.out.println("m1.lookingAt() start = " + m1.start()
+ " end = " + m1.end());
if (m2.lookingAt())
System.out.println("m2.lookingAt() start = " + m2.start()
+ " end = " + m2.end());
if (m1.matches()) // No reset() necessary
System.out.println("m1.matches() start = " + m1.start()
+ " end = " + m1.end());
if (m2.matches())
System.out.println("m2.matches() start = " + m2.start()
+ " end = " + m2.end());
}
}
} ///:~
Setting Case Sensitivity in a Regular Expression
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] argv) throws Exception {
CharSequence inputStr = "Abc";
String patternStr = "abc";
// Compile with case-insensitivity
Pattern pattern = Pattern.rupile(patternStr, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.matches();
// Use an inline modifier
matchFound = pattern.matches("abc", "aBc");
matchFound = pattern.matches("(?i)abc", "aBc");
matchFound = pattern.matches("a(?i)bc", "aBc");
}
}
Show use of Pattern.CANON_EQ
/*
* 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;
/**
* CanonEqDemo - show use of Pattern.CANON_EQ, by comparing varous ways of
* entering the Spanish word for "equal" and see if they are considered equal by
* the RE-matching engine.
*
* @version $Id: CanonEqDemo.java,v 1.3 2004/03/21 20:06:20 ian Exp $
*/
public class CanonEqDemo {
public static void main(String[] args) {
String pattStr = "\u00e9gal"; // Zgal
String[] input = { "\u00e9gal", // Zgal - this one had better match :-)
"e\u0301gal", // e + "Combining acute accent"
"e\u02cagal", // e + "modifier letter acute accent"
"e"gal", // e + single quote
"e\u00b4gal", // e + Latin-1 "acute"
};
Pattern pattern = Pattern.rupile(pattStr, Pattern.CANON_EQ);
for (int i = 0; i < input.length; i++) {
if (pattern.matcher(input[i]).matches()) {
System.out.println(pattStr + " matches input " + input[i]);
} else {
System.out.println(pattStr + " does not match input "
+ input[i]);
}
}
}
}
Simple example of using Regular Expressions functionality in String 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.
*/
/**
* Simple example of using RE functionality in String class.
* @author Ian F. Darwin, http://www.darwinsys.ru/
* @version $Id: REString.java,v 1.4 2004/02/23 02:37:34 ian Exp $
*/
public class REString {
public static void main(String[] argv) {
String pattern = "^Q[^u]\\d+\\..*";
String input = "QA777. is the next flight. It is on time.";
boolean found = input.matches(pattern);
System.out.println(""" + pattern + """ +
(found ? " matches " : " doesn"t match "") + input + """);
}
}
Simple Negative Lookahead
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) throws Exception {
String regex = "test (?!Test)[A-Z]\\w+";
Pattern pattern = Pattern.rupile(regex);
String candidate = "this is a test ";
Matcher matcher = pattern.matcher(candidate);
String tmp = null;
while (matcher.find()) {
tmp = matcher.group();
System.out.println("MATCH:" + tmp);
}
}
}
Simple Pattern
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternMethodExample {
public static void main(String args[]) {
reusePatternMethodExample();
}
public static void reusePatternMethodExample() {
Pattern p = Pattern.rupile("\\d");
Matcher matcher = p.matcher("5");
boolean isOk = matcher.matches();
System.out.println("original pattern matches " + isOk);
String tmp = p.pattern();
Pattern p2 = Pattern.rupile(tmp);
matcher = p.matcher("5");
isOk = matcher.matches();
System.out.println("second pattern matches " + isOk);
}
}
Simple Positive Lookahead
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
String regex = "(?=^255).*";
Pattern pattern = Pattern.rupile(regex);
String candidate = "255.0.0.1";
Matcher matcher = pattern.matcher(candidate);
String ip = "not found";
if (matcher.find())
ip = matcher.group();
String msg = "ip: " + ip;
System.out.println(msg);
}
}
Simple Positive Lookbehind
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) throws Exception {
String regex = "(?<=http://)\\S+";
Pattern pattern = Pattern.rupile(regex);
String candidate = "http://www.a.ru.";
Matcher matcher = pattern.matcher(candidate);
while (matcher.find()) {
String msg = ":" + matcher.group() + ":";
System.out.println(msg);
}
}
}
Tabs and newlines in the pattern are ignored as well
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] argv) throws Exception {
CharSequence inputStr = "a b";
String patternStr = "a b";
// Compile without comments
Pattern pattern = Pattern.rupile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.matches();
// Compile with comments
pattern = Pattern.rupile(patternStr, Pattern.ruMENTS);
matcher = pattern.matcher(inputStr);
matchFound = matcher.matches();
matchFound = pattern.matches("(?x)a \t\n \\s b", inputStr);
}
}
The inline modifier can also contain pattern characters using the form (?x:abc)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] argv) throws Exception {
CharSequence inputStr = "a b";
String patternStr = "a b";
// Compile without comments
Pattern pattern = Pattern.rupile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.matches();
// Compile with comments
pattern = Pattern.rupile(patternStr, Pattern.ruMENTS);
matcher = pattern.matcher(inputStr);
matchFound = matcher.matches(); // false
// Use an inline modifier
matchFound = pattern.matches("a b", inputStr);
matchFound = pattern.matches("(?x)a b", inputStr);
}
}
Use a character set
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] argv) throws Exception {
CharSequence inputStr = "Abc";
String patternStr = "abc";
// Compile with case-insensitivity
Pattern pattern = Pattern.rupile(patternStr, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.matches();
matchFound = pattern.matches("[a-c]+", "aBc");
matchFound = pattern.matches("(?i)[a-c]+", "aBc");
}
}
Use an inline modifier: a (?x: b)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] argv) throws Exception {
CharSequence inputStr = "a b";
String patternStr = "a b";
// Compile without comments
Pattern pattern = Pattern.rupile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.matches();
// Compile with comments
pattern = Pattern.rupile(patternStr, Pattern.ruMENTS);
matcher = pattern.matcher(inputStr);
matchFound = matcher.matches(); // false
// Use an inline modifier
matchFound = pattern.matches("a (?x: b )", inputStr);
}
}
Use an inline modifier: (?x)a [\\ ] b
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] argv) throws Exception {
CharSequence inputStr = "a b";
String patternStr = "a b";
// Compile without comments
Pattern pattern = Pattern.rupile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.matches();
// Compile with comments
pattern = Pattern.rupile(patternStr, Pattern.ruMENTS);
matcher = pattern.matcher(inputStr);
matchFound = matcher.matches(); // false
// Use an inline modifier
matchFound = pattern.matches("(?x)a [\\ ] b", inputStr);
}
}
Use an inline modifier: x)a \\s b
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] argv) throws Exception {
CharSequence inputStr = "a b";
String patternStr = "a b";
// Compile without comments
Pattern pattern = Pattern.rupile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.matches();
// Compile with comments
pattern = Pattern.rupile(patternStr, Pattern.ruMENTS);
matcher = pattern.matcher(inputStr);
matchFound = matcher.matches(); // false
// Use an inline modifier
matchFound = pattern.matches("(?x)a \\s b", inputStr);
}
}
Use enclosing form
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] argv) throws Exception {
CharSequence inputStr = "Abc";
String patternStr = "abc";
// Compile with case-insensitivity
Pattern pattern = Pattern.rupile(patternStr, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.matches();
matchFound = pattern.matches("((?i)a)bc", "aBc");
matchFound = pattern.matches("(?i:a)bc", "aBc");
matchFound = pattern.matches("a((?i)b)c", "aBc");
matchFound = pattern.matches("a(?i:b)c", "aBc");
}
}
Using the find(int) Method
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
Pattern p = Pattern.rupile("test", Pattern.CASE_INSENSITIVE);
String candidateString = "Test.";
Matcher matcher = p.matcher(candidateString);
matcher.find(0);
System.out.println(matcher.group());
}
}
Using the find() Method from Matcher
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
Pattern p = Pattern.rupile("Java");
String candidateString = "Java Java Java.";
Matcher matcher = p.matcher(candidateString);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
Using the lookingAt Method
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
Pattern p = Pattern.rupile("test");
Matcher matcher = p.matcher("this is a test");
// display the output for the candidate
System.out.println(matcher.lookingAt());
}
}
Validation Test With Pattern And Matcher
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) throws Exception {
Pattern p = Pattern.rupile("Java \\d");
String candidate = "this is a Java test";
Matcher m = p.matcher(candidate);
System.out.println("result=" + m.find());
}
}