Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Matcher.find()

Searches for the next match of the pattern anywhere in the string.

Available since: Java 1.4

Syntax

public boolean find()

Return value

booleantrue if a match is found; it is then available through group().

Examples

Every email address in a text, with its position:

void main() {
    String text = "Write to anna@example.com or oleg@test.org";
    Matcher m = Pattern.compile("[\\w.]+@[\\w.]+\\.\\w+").matcher(text);
    while (m.find()) {
        IO.println(m.group() + " at " + m.start());
    }
}

Output:

anna@example.com at 9
oleg@test.org at 29

Checking whether a string contains a digit:

void main() {
    Pattern digit = Pattern.compile("\\d");
    IO.println(digit.matcher("abc1").find());
    IO.println(digit.matcher("abc").find());
}

Output:

true
false

Notes

Each find() call continues from where the previous match ended, so it is called in a while loop. To check the whole string, use matches(). start() and end() return the match boundaries.

See also

  • Matcher.group() — Returns the text of the current match or of one of its parenthesized groups.
  • Matcher.matches() — Checks whether the whole string matches the pattern.
  • Matcher.results() — Returns all matches at once as a stream — a short replacement for a find() loop.
  • Pattern.matcher() — Creates a Matcher that searches for the pattern in a specific string.

Related recipes

In the tutorial

  • Regular expressions — Regular expressions in Java: matches, replaceAll, splitting by a pattern, the Pattern and Matcher classes, groups and escaping backslashes.

Thanks for reading!

Donate to the site — we work hard for you.