使用正则表达式获取字符串中模式的索引

时间:2012-01-20 08:19:33

标签: java regex string

我想在字符串中搜索特定模式。

正则表达式类是否提供字符串中模式的位置(字符串中的索引)?
该模式可能会出现1次以上 任何实际的例子?

3 个答案:

答案 0 :(得分:142)

使用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());
    }
}

答案 1 :(得分:3)

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

答案 2 :(得分:-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");
      }
   }
}

结果

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