109

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?

Cratylus
  • 52,998
  • 69
  • 209
  • 339

3 Answers3

204

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());
    }
}
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
6

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};
}
Ar maj
  • 1,974
  • 1
  • 16
  • 16
-3
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
Shadow
  • 6,161
  • 3
  • 20
  • 14
  • 2
    Please comment when downvoting! @Shadow I assume this has been downvoted as it does not, as the OP request, give the index of the match... – El Ronnoco Jan 20 '12 at 09:13
  • 4
    Okay... I downvoted because this answer does not address the question. –  Jan 20 '12 at 10:23
  • 3
    Your regex is faulty, too. The first `(.*)` originally consumes the whole string, then it backs off just far enough to let `(\d+)` match one digit, leaving then the second `(.*)` to consume whatever's left. Not a particularly useful result, I'd say. Oh, and you left `group(3)` out of your results. – Alan Moore Jan 20 '12 at 11:06
  • 3
    Doesn't give the index – mez.pahlan Jun 30 '16 at 21:41