Sub topic 14
Splitting and Replacing with Regular Expressions
A regular expression, or regex, is a rule for finding text. Java uses regular expressions in methods such as split and replaceAll.
A regex can match simple text, such as a comma, or a group of characters, such as one or more spaces. This chapter shows how to use both kinds.
Split text into fields
The split method cuts a string at each match. It returns an array, which is a collection of values in order.
Save this example as SplitText.java:
import java.util.Arrays;
class SplitText {
public static void main(String[] args) {
String[] fields = "red,blue,".split(",", -1);
System.out.println(Arrays.toString(fields));
String[] items = "tea|milk|".split("\\|", -1);
System.out.println(Arrays.toString(items));
}
}Compile it with javac SplitText.java, then run it with java SplitText. The output is:
[red, blue, ]
[tea, milk, ]Arrays.toString displays the array’s values in brackets. The last value in each array is an empty string: there is no text after the final separator.
The second argument, -1, tells split to keep empty fields at the end. Without it, split normally drops those trailing empty fields. Keeping them matters when an empty field is still part of your data.
Special characters in a regex
The vertical bar, |, has a special meaning in a regex. To match an actual |, the regex needs a backslash before it: \|.
In Java code, write that regex as "\\|". The two backslashes in the Java string produce one backslash in the regex. A period, ., is also special; use "\\." to match an actual period.
If a separator comes from a variable, Pattern.quote(separator) creates a regex that matches its text literally. Import java.util.regex.Pattern to use it.
Replace matching text
Use replace when you want to replace exact text. Use replaceAll when you want the text to find to follow a regex.
Save this example as ReplaceText.java:
import java.util.regex.Matcher;
class ReplaceText {
public static void main(String[] args) {
String text = "Room 12";
System.out.println(text.replace("Room", "Desk"));
System.out.println(text.replaceAll("\\s+", " "));
System.out.println(
text.replaceAll("[0-9]+", Matcher.quoteReplacement("$5"))
);
}
}Compile and run it as you did the first example. Its output is:
Desk 12
Room 12
Room $5Here, \\s tells the regex to match a whitespace character, such as a space or tab. The + means “one or more.” So replaceAll("\\s+", " ") replaces each run of whitespace with one space.
The regex [0-9]+ matches one or more digits from 0 through 9. In replacement text, $ and backslash can have special meanings. Matcher.quoteReplacement makes them ordinary text, so "$5" is inserted as written.
These methods return new strings. They do not change the original text.
Practice
Exercise
What does "a,b,".split(",", -1) contain, and why?
Show answer
It contains "a", "b", and an empty string. The -1 keeps the empty field after the final comma.
Exercise
Which method would you use to replace each run of digits in a string with "X"?
Show answer
Use text.replaceAll("[0-9]+", "X").