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?
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?
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