Regular expressions

The Pattern class represents a regular expression pattern.

The Matcher class represents an engine that performs match operations.

The String contains some methods that work with regular expressions.

Regular expression example

class Pattern

The Pattern class represents a regular expression pattern. Follow link to read common regular expression syntax.

method description
static method
compile( regex) Compiles the given regular expression into a pattern.
compile( regex,      flags) Compiles the given regular expression into a pattern with the given flags.
matches( regex, input) Compiles the given regular expression and attempts to match the given input against it.
quote( s) Returns a literal pattern String for the specified String.
instance methods
asPredicate() Creates a predicate which can be used to match a string.
flags() Returns this pattern's match flags.
matcher( input) Creates a matcher that will match the given input against this pattern.
pattern() Returns the regular expression from which this pattern was compiled.
split( input) Splits the given input sequence around matches of this pattern.
split( input, limit)

Splits the given input sequence around matches of this pattern.

The limit parameter specifies the number of times the pattern is applied and therefore affects the length of the resulting array. A non-positive value means that the pattern will be applied as many times as possible and the array can have any length.

splitAsStream( input) Creates a stream from the given input sequence around matches of this pattern.
toString() Returns the string representation of this pattern.

class Matcher

method description
static method
quoteReplacement(s) Returns a literal replacement String for the specified String.
instance methods
appendReplacement( sb,repl) Implements a non-terminal append-and-replace step.
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while (m.find()) {
    m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
// one dog two dogs in the yard
System.out.println(sb.toString());