【问题标题】:Get the index of a pattern in a string using regex使用正则表达式获取字符串中模式的索引
【发布时间】:2012-02-14 20:19:08
【问题描述】:

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

正则表达式类是否提供模式在字符串中的位置(字符串中的索引)?
模式的出现次数可能超过 1 次。
有什么实际的例子吗?

【问题讨论】:

标签: java regex string


【解决方案1】:

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

【讨论】:

    【解决方案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
    

    【讨论】:

    • 投反对票时请发表评论! @Shadow 我认为这已被否决,因为它没有作为 OP 请求提供匹配的索引...
    • 好吧...我投了反对票,因为这个答案没有解决问题。
    • 你的正则表达式也有问题。第一个 (.*) 最初消耗整个字符串,然后它后退到足以让 (\d+) 匹配一个数字,然后让第二个 (.*) 消耗剩下的任何内容。我想说,这不是一个特别有用的结果。哦,你在结果中留下了group(3)
    • 不给索引
    【解决方案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};
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-16
      • 2021-12-03
      • 2015-11-28
      • 1970-01-01
      相关资源
      最近更新 更多