Java Reference
In-Depth Information
Let's consider the following 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.”
You want to find all numbers in the text (e.g., 125, 100, and 75) and replace them as follows:
“100” by “a hundred”
“> 100” by “more than a hundred”
“< 100” by “less than a hundred”
After replacement, the above text should read as follows:
"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."
To accomplish this task, you need to find all numbers embedded in the text, compare the found number with
100, and decide on the replacement text. Such a situation also arises when you find and replace text using a text editor.
The text editor highlights the word you were searching for, you enter a new word, and text editor does the replacement
for you. You can also create a find/replace program as found in text editors using these two methods. Typically, these
methods are used in conjunction with the find() method of the Matcher class. The steps that are performed to
accomplish find and replace texts using these two methods are outlined below.
Create a
Pattern object.
Create a
Matcher object.
Create a
StringBuffer object to hold the result.
Use the
find() method in a loop to match the pattern.
Call the
appendReplacement() and appendTail() methods depending on the position of the
found match.
Let's create a Pattern by compiling the regular expression. Since you want to find all numbers, your regular
expression would be \b\d+\b . Note the first and last \b . They specify that you are interested in numbers only on
word boundaries.
String regex = "\\b\\d+\\b";
Pattern p = Pattern.compile(regex);
Create a Matcher by associating the pattern with the text.
String 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.";
Matcher m = p.matcher(text);
Create a StringBuffer to hold the new text
StringBuffer sb = new StringBuffer();
 
Search WWH ::




Custom Search