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


Answers:


166

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

5

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

2
投票时请发表评论!@Shadow我认为这已被否决,因为它没有作为OP请求提供比赛的索引...
El Ronnoco 2012年

4
好吧...我不赞成投票,因为此答案不能解决问题。

3
您的正则表达式也有问题。第一个(.*)最初消耗了整个字符串,然后回退了足够远的距离以(\d+)匹配一个数字,然后第二个(.*)消耗了剩下的任何东西。我会说这不是特别有用的结果。哦,您忘group(3)了结果了。
艾伦·摩尔

2
没有给出索引
piratemurray
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.