Regex with String Methods

Naveen AnamaneniUpdated · 3 min read
mediumJava 25javaregexstrings

You don't always need Pattern and Matcher. Four String methods accept a regular expression directly: matches, split, replaceAll and replaceFirst. They're perfect for quick, one-off jobs like checking a name or cleaning spaces. The catch is that their argument is a pattern, not plain text, so characters like ., | and $ behave differently than you might expect.

The Four Methods

Shortcuts.java▶ Try it
import java.util.Arrays;
 
public class Shortcuts {
    public static void main(String[] args) {
        System.out.println("Navika".matches("[A-Z][a-z]+"));
        System.out.println("navika".matches("[A-Z][a-z]+"));
 
        System.out.println(Arrays.toString("a1b22c333".split("\\d+")));
        String cities = "Pune,  Delhi ,Chennai";
        System.out.println(Arrays.toString(cities.split("\\s*,\\s*")));
 
        System.out.println("Hello    World  !".replaceAll("\\s+", " "));
        System.out.println("call 98765 43210 now".replaceAll("\\d", "*"));
        System.out.println("price: $45.50".replaceFirst("\\$", "Rs. "));
    }
}
Output
true
false
[a, b, c]
[Pune, Delhi, Chennai]
Hello World !
call ***** ***** now
price: Rs. 45.50

How it works

  1. matches(regex) is true only if the whole string fits the pattern.
  2. split(regex) cuts the string wherever the pattern matches. \\s*,\\s* splits on commas and swallows the spaces around them, so the pieces come out clean.
  3. replaceAll(regex, replacement) replaces every match; replaceFirst only the first.
  4. \\$ escapes the dollar sign, which is special in patterns.

Three Surprises

1. A dot means "any character".

Dots.java▶ Try it
import java.util.Arrays;
import java.util.regex.Pattern;
 
public class Dots {
    public static void main(String[] args) {
        System.out.println("1.5.2".split(".").length);
        System.out.println(Arrays.toString("1.5.2".split("\\.")));
        System.out.println(Arrays.toString("1.5.2".split(Pattern.quote("."))));
    }
}
Output
0
[1, 5, 2]
[1, 5, 2]

split(".") splits on every character, leaving only empty pieces, which split then drops, so the array is empty. Escape the dot, or wrap plain text in Pattern.quote.

2. $ and \ are special in the replacement. In replaceAll, $1 means "group 1". To insert a literal dollar sign, escape it (\\$) or use Matcher.quoteReplacement(text), which escapes it for you. This matters when the replacement comes from user data.

3. Trailing empty pieces disappear. "a,b,,".split(",") gives [a, b]. Pass a limit of -1 to keep them: "a,b,,".split(",", -1) gives [a, b, , ], which matters when reading CSV data with blank last columns.

MethodArgument isWatch out for
replace(a, b)Plain textNothing special
replaceAll(regex, repl)Pattern, and $ in replEscape . $ \ | etc.
split(regex)PatternDots, pipes; trailing empties dropped
matches(regex)PatternMust match the whole string

Common Mistakes

Splitting on ".", "|" or "+" without escaping. Use "\\.", "\\|", "\\+".

Using replaceAll when you meant plain text. replace is simpler and has no special characters.

Putting user text into a replacement unescaped. A $ in it throws or inserts the wrong thing; use Matcher.quoteReplacement.

Practice

  1. Easy: Clean " Advitha Anamaneni " into "Advitha Anamaneni" using strip() and one replaceAll.
  2. Harder: Split the version string "25.0.5" into numbers and print the major version. Then split "a|b|c" on the pipe character correctly.

Quick check: Regex with String methods

4 questions
1Which String method treats its argument as plain text?
2What does "1.5.2".split(".") return?
3What does "x y".replaceAll("\\s+", " ") return?
4Why precompile a Pattern for use in a loop?

Key Takeaways

Was this tutorial helpful?

Lesson 212 of 482