Regular Expression Processing

A regular expression is a pattern. And we use the pattern to find matches in other strings.

There are two classes that support regular expression processing: Pattern and Matcher.

Pattern define a regular expression. Matcher do the matching with the pattern.

Pattern

The Pattern class defines no constructors. A pattern is created by calling the compile( ) factory method.

One of its forms is shown here:

static Pattern compile(String pattern)

pattern parameter is the regular expression.

Matcher is created by calling the matcher( ) factory method defined by Pattern. It is shown here:

Matcher matcher(CharSequence str)

str is the character sequence that the pattern will be matched against.

CharSequence is an interface that defines a read-only set of characters. It is implemented by the String class. You can pass a string to matcher( ).

Matcher

Once you have created a Matcher, you will use its methods to do various pattern matching operations.

Matcher defines the following methods:

boolean matches( )
determines whether the character sequence matches the pattern. It returns true if the sequence and the pattern match, and false otherwise.
boolean find( )
To determine if a subsequence of the input sequence matches the pattern. It returns true if there is a matching subsequence and false otherwise. This method can be called repeatedly to find all matching subsequences.
String group( )
returns a string containing the last matching sequence by calling group( ).
int start( )
returns the index within the input sequence of the current match
int end( )
return the index past the end of the current match.
String replaceAll(String newStr)
replace all occurrences of a matching sequence with another sequence. The updated input sequence is returned as a string.

In general, a regular expression is comprised of normal characters, character classes, wildcard characters, and quantifiers.

Home 
  Java Book 
    Essential Classes  

Matcher:
  1. Regular Expression Processing
  2. Normal character
  3. Wildcard character
  4. Using Wildcards and Quantifiers
  5. Greedy behavior
  6. Working with Classes of Characters
  7. Using replaceAll( )
  8. Using split( )
  9. Matcher: appendReplacement(StringBuffer sb,String replacement)
  10. Matcher.appendTail(StringBuffer sb)
  11. Matcher: find()
  12. Matcher: group()
  13. Matcher: group(int group)
  14. Matcher: groupCount()
  15. Matcher: lookingAt()
  16. Matcher: matches()
  17. Matcher: replaceAll(String text)
  18. Matcher: start()