Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Regular expressions

A regular expression is a pattern that describes a set of strings: "digits only", "a word of letters", "an email address". It is used to validate input, find pieces of text and replace them. In Java a pattern is written as an ordinary string.

matches

The matches() method checks whether the whole string fits the pattern. \d means any digit, and + means "one or more times":

void main() {
    IO.println("12345".matches("\\d+"));
    IO.println("123a5".matches("\\d+"));
}

Output:

true
false

In a Java string the backslash must be escaped, so the pattern \d+ is written as "\\d+".

Syntax basics

A few of the most useful pattern elements:

ElementMeaning
\d, \w, \sa digit, a letter or digit or _, a whitespace character
[abc], [a-z]one character from a set or range
.any character
*, +, ?zero or more, one or more, zero or one time
{3}, {2,4}exactly 3 times, 2 to 4 times
void main() {
    String code = "[A-Z]{2}-\\d{3}";
    IO.println("AB-123".matches(code));
    IO.println("ab-123".matches(code));
    IO.println("AB-12".matches(code));
}

Output:

true
false
false

replaceAll

replaceAll() replaces every fragment that matches the pattern. \s+ means one or more whitespace characters in a row:

void main() {
    String text = "Too    many     spaces";
    IO.println(text.replaceAll("\\s+", " "));
    IO.println("Phone: 555-123-4567".replaceAll("\\d", "*"));
}

Output:

Too many spaces
Phone: ***-***-****

Splitting by a pattern

split() also takes a regular expression. That lets you split a string by several separators at once:

void main() {
    String tags = "java, kotlin;  scala,go";
    String[] parts = tags.split("[,;]\\s*");
    IO.println(Arrays.toString(parts));
}

Output:

[java, kotlin, scala, go]

[,;] is a comma or a semicolon, \s* any number of spaces after it.

Pattern and Matcher

To find all matches inside a text, compile the pattern into a Pattern object and then walk through the matches with a Matcher. Parts of the pattern in parentheses — groups — can be read separately:

void main() {
    String text = "Anna: 30 years, Oleg: 25 years";
    Pattern pattern = Pattern.compile("(\\w+): (\\d+)");
    Matcher matcher = pattern.matcher(text);
 
    while (matcher.find()) {
        IO.println(matcher.group(1) + " -> " + matcher.group(2));
    }
}

Output:

Anna -> 30
Oleg -> 25

find() looks for the next match and returns false when there are no more. By default \w in Java matches only Latin letters, digits and _; for letters of any alphabet use \p{L}. The Pattern and Matcher classes live in the java.util.regex package: the short program form imports it automatically, the classic form needs import java.util.regex.*;.

Common mistake

split() takes a regular expression, and in it a dot means "any character". So splitting by "." gives an empty array:

void main() {
    String ip = "192.168.0.1";
    IO.println(ip.split(".").length);
    IO.println(ip.split("\\.").length);
}

Output:

0
4

Escape special characters: "\\.", "\\|", "\\+". replaceAll() has the same trap; if you do not need a pattern, use replace().

Thanks for reading!

Donate to the site — we work hard for you.