Sub topic 14
Splitting and Replacing with Regular Expressions
A regular expression, or regex, is a pattern for finding text. It can match a fixed piece of text, such as a comma, or a broader pattern, such as one or more spaces.
Java’s String class uses regex patterns in several methods. This chapter focuses on split, replaceAll, and replaceFirst. You will also learn when the simpler replace method is a better choice.
Splitting text into fields
A field is one piece of text in a larger piece of data. A separator is the text between fields. For example, in red,blue, the comma separates two fields.
The split method finds each separator and returns an array, or ordered list, of the pieces between them. The separators do not appear in the result.
The first argument to split is a regex. A second argument, called the limit, controls how the result is split and whether trailing empty fields are kept.
Save this program as SplitDemo.java and run it:
import java.util.Arrays;
import java.util.regex.Pattern;
class SplitDemo {
public static void main(String[] args) {
String text = "red,blue,";
String[] fields = text.split(",", -1);
System.out.println(Arrays.toString(fields));
System.out.println(fields.length);
System.out.println(Arrays.toString(text.split(",")));
System.out.println(Arrays.toString(
"red,blue,green".split(",", 2)));
System.out.println(Arrays.toString(
"a.b.c".split("\\.")));
String separator = ".";
System.out.println(Arrays.toString(
"a.b.c".split(Pattern.quote(separator), -1)));
System.out.println(Arrays.toString(
"red blue\tgreen".split("\\s+")));
System.out.println("".split(",").length);
}
}The output is:
[red, blue, ]
3
[red, blue]
[red, blue,green]
[a, b, c]
[a, b, c]
[red, blue, green]
1The first result has three fields: red, blue, and an empty string after the last comma. The next section explains why the result changes when the limit is left out.
The last line shows a useful edge case: splitting an empty string produces one field, which is itself empty. Checking the array’s length makes that clear.
Choosing a limit
| Limit | What happens |
|---|---|
| Negative, such as `-1` | Splits as often as possible and keeps trailing empty fields. |
| Zero, or left out | Splits as often as possible but removes trailing empty fields. |
| Positive, such as `2` | Returns at most that many fields. The last field holds the remaining text. |
A trailing empty field is an empty field at the end. In "red,blue,", the final comma has no text after it. A negative limit keeps that empty field. With no limit, split removes it.
A positive limit can be useful when you only want to separate the first part. For example, splitting "red,blue,green" with a limit of 2 gives red and blue,green.
An empty field can also occur at the start or between separators. For example, ",red,,blue".split(",", -1) has empty fields before red and between red and blue.
Writing regex patterns in Java
Some characters have special meanings in a regex. They are called metacharacters. For example, a dot matches almost any single character; it does not normally mean a literal dot.
A literal character is the exact character itself. To match a literal dot in a regex, put a backslash before it. In a Java string, write that backslash as \\, so the Java string for a literal dot is "\\.".
This is why SplitDemo uses split("\\.") rather than split(".").
| Java string holding a regex | What the regex matches |
|---|---|
| `","` | A comma |
| `"."` | Almost any single character |
| `"\\."` | A literal dot |
| `"\\s+"` | One or more whitespace characters |
| `"[0-9]+"` | One or more digits from `0` to `9` |
Whitespace includes spaces, tabs, and line breaks. The + means “one or more” of the pattern just before it. Thus, "\\s+" treats a run of spaces or tabs as one separator.
The square brackets in [0-9] define a character class: a set of characters to match. Here, the set contains the digits 0 through 9.
Using a separator supplied as text
What if a separator comes from a user or another part of your program? It might contain a dot or another regex metacharacter.
Pattern.quote(separator) creates a regex that matches the separator literally. In SplitDemo, it makes the value "." mean an actual dot. This is safer than trying to add backslashes yourself.
Replacing text
Java offers three useful replacement methods:
replacesearches for literal text and replaces every occurrence.replaceAllsearches with a regex and replaces every match.replaceFirstsearches with a regex and replaces only the first match.
Use replace when you need exact text and do not need a pattern. This avoids accidentally giving special meaning to regex metacharacters.
Save this program as ReplaceDemo.java and run it:
import java.util.regex.Matcher;
class ReplaceDemo {
public static void main(String[] args) {
String text = "cat scatter cat";
System.out.println(text.replace("cat", "dog"));
System.out.println(text.replaceAll("\\bcat\\b", "dog"));
System.out.println(text.replaceFirst("\\bcat\\b", "dog"));
System.out.println(
"red blue\tgreen".replaceAll("\\s+", " "));
System.out.println(
"12-34".replaceAll("([0-9]+)-([0-9]+)", "$2/$1"));
String replacement = "$5\\box";
System.out.println(
"cost: VALUE".replaceAll(
"VALUE", Matcher.quoteReplacement(replacement)));
}
}The output is:
dog sdogter dog
dog scatter dog
dog scatter cat
red blue green
34/12
cost: $5\boxThe first line shows that literal replace finds cat even inside scatter. In the next two lines, \\b represents a word boundary, a position at the edge of a word. The pattern "\\bcat\\b" therefore matches the separate word cat in this example, but not the letters inside scatter.
The whitespace example replaces each run of whitespace with one space. Both replaceAll and replaceFirst return a new string; they do not change the original string.
Reusing parts of a match
A group is part of a regex enclosed in parentheses. In the pattern "([0-9]+)-([0-9]+)", the first group matches 12, and the second matches 34.
In a replaceAll replacement, $1 means the text matched by the first group, and $2 means the text matched by the second. The replacement "$2/$1" puts the second group first, then a slash, then the first group. That turns 12-34 into 34/12.
Treating replacement text literally
The replacement argument to replaceAll and replaceFirst has its own special rules. A dollar sign can refer to a group, and a backslash can also have a special meaning.
If replacement text may contain either character, use Matcher.quoteReplacement to make it literal. ReplaceDemo does this for "$5\\box", so the output contains the dollar sign and backslash as text.
This differs from Pattern.quote:
- Use
Pattern.quotefor text that must be matched literally. - Use
Matcher.quoteReplacementfor text that must be inserted literally. - Use
replacewhen both the text to find and the replacement are literal.
Common errors
If a regex has invalid syntax, Java throws a PatternSyntaxException. For example, an opening square bracket without a closing bracket is not a complete character class.
A valid pattern can still give the wrong result. Check whether you meant a literal dot or the regex dot, and check whether you need to keep trailing empty fields. When a result looks surprising, print the array length as well as its contents.
Avoid accepting arbitrary regex patterns from untrusted users without limits. Some patterns can take a long time to process large inputs. If users only need to supply exact text, quote that text with Pattern.quote instead.
Exercises
Exercise
What does "sun,moon,".split(",", -1) return, and why is the limit useful?
Show answer
It returns three fields: "sun", "moon", and "". The negative limit keeps the trailing empty field after the last comma.
Exercise
Which method would you use to replace every literal dot in a string with a dash?
Show answer
Use replace(".", "-"). It treats the dot as literal text, so no regex escaping is needed.