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.
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( ).
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.
- Regular Expression Processing
- Normal character
- Wildcard character
- Using Wildcards and Quantifiers
- Greedy behavior
- Working with Classes of Characters
- Using replaceAll( )
- Using split( )
- Matcher: appendReplacement(StringBuffer sb,String replacement)
- Matcher.appendTail(StringBuffer sb)
- Matcher: find()
- Matcher: group()
- Matcher: group(int group)
- Matcher: groupCount()
- Matcher: lookingAt()
- Matcher: matches()
- Matcher: replaceAll(String text)
- Matcher: start()