Get the index of a pattern in a string using regex
Solution 1:
Use Matcher:
public static void printMatches(String text, String regex) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
// Check all occurrences
while (matcher.find()) {
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end());
System.out.println(" Found: " + matcher.group());
}
}
Solution 2:
special edition answer from Jean Logeart
public static int[] regExIndex(String pattern, String text, Integer fromIndex){
Matcher matcher = Pattern.compile(pattern).matcher(text);
if ( ( fromIndex != null && matcher.find(fromIndex) ) || matcher.find()) {
return new int[]{matcher.start(), matcher.end()};
}
return new int[]{-1, -1};
}