Java Reference
In-Depth Information
// Convert the text into an integer for comparing
int num = Integer.parseInt(matchedText);
// Prepare the replacement text
if (num == 100) {
replacementText = "a hundred";
}
else if (num < 100) {
replacementText = "less than a hundred";
}
else {
replacementText = "more than a hundred";
}
m.appendReplacement(sb, replacementText);
}
// Append the tail
m.appendTail(sb);
// Display the old and new text
System.out.println("Old Text: " + text);
System.out.println("New Text: " + sb.toString());
}
}
Old Text: A train carrying 125 men and women was traveling at the speed of 100 miles per hour.
The train fare was 75 dollars per person.
New Text: A train carrying more than a hundred men and women was traveling at the speed of a
hundred miles per hour. The train fare was less than a hundred dollars per person.
Summary
A regular expression is a sequence of characters used as a pattern to match some text. Java provides comprehensive
support for using regular expressions through the Pattern and Matcher classes. Several convenience methods for
using regular expression exist in the String class.
A Pattern object represents a compiled regular expression. A Matcher object is used to associate a Pattern with
an input text to be searched for the pattern. The find() method of the Matcher class is used to find a match for the
pattern in the input text. Regular expressions allow you to use groups. Groups are automatically numbered from 1 and
N. The first group from left is number 1. A special group 0 exists that is the entire regular expression. Starting with
Java 7, you can also name groups. You can refer to the groups by numbers and their names.
 
Search WWH ::




Custom Search