Find all occurrences of a pattern in a String

2

I need to use regular expressions to find patterns in a text. It would be better for me if there were a method equal to search() of Python, which returns a vector with all occurrences of that pattern. Is there a similar method in Java?

    
asked by anonymous 19.02.2018 / 21:45

1 answer

3

The class Pattern serves exactly that , it represents a regex. The helper 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 output:

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.

    
19.02.2018 / 23:04