Get the index of a pattern in a string using regex

JavaRegexString

Java Problem Overview


I want to search a string for a specific pattern.

Do the regular expression classes provide the positions (indexes within the string) of the pattern within the string?
There can be more that 1 occurences of the pattern.
Any practical example?

Java Solutions


Solution 1 - Java

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

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};
}

Solution 3 - Java

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

public class RegexMatches
{
    public static void main( String args[] ){

      // String to be scanned to find the pattern.
      String line = "This order was places for QT3000! OK?";
      String pattern = "(.*)(\\d+)(.*)";

      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);

      // Now create matcher object.
      Matcher m = r.matcher(line);
      if (m.find( )) {
         System.out.println("Found value: " + m.group(0) );
         System.out.println("Found value: " + m.group(1) );
         System.out.println("Found value: " + m.group(2) );
      } else {
         System.out.println("NO MATCH");
      }
   }
}

Result

Found value: This order was places for QT3000! OK?
Found value: This order was places for QT300
Found value: 0

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCratylusView Question on Stackoverflow
Solution 1 - JavaJean LogeartView Answer on Stackoverflow
Solution 2 - JavaAr majView Answer on Stackoverflow
Solution 3 - JavaShadowView Answer on Stackoverflow