Find all occurrences of a pattern in a String

Asked

Viewed 667 times

2

I need to use regular expressions to find patterns in a text. It would be better for me if there was a method like search() Python, which returns an array with all occurrences of this pattern. There is a similar method in Java?

1 answer

3


To class Pattern serves exactly for this, it represents a regex. A auxiliary class Matcher is used to control the search.

To search for a regular expression in the middle of a text:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class TesteRegex {

    private static final Pattern ABC = Pattern.compile("A+B+C+");

    public static void main(String[] args) {
        String texto = "123 456 7890 ABx AAACCC AABBCC hjkhkk ABBBBCCC djsdhj ABC kdjk.";
        Matcher m = ABC.matcher(texto);
        while (m.find()) {
            System.out.println("Achou nas posições " + m.start() + "-" + m.end() + ": "
                    + texto.substring(m.start(), m.end()));
        }
    }
}

Here’s the way out:

Achou nas posições 24-30: AABBCC
Achou nas posições 38-46: ABBBBCCC
Achou nas posições 54-57: ABC

See here working on ideone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.