2012-01-20 26 views
64

我想搜索特定模式的字符串。使用正則表達式獲取字符串中模式的索引

正則表達式類提供字符串中模式的位置(字符串內的索引)嗎?
可以有更多的1模式發生。
任何實際的例子?

+2

http://docs.oracle.com/javase/6 /docs/api/java/util/regex/Matcher.html –

回答

118

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

請在投票時發表評論! @Shadow我認爲這已經被低估了,因爲它沒有,因爲OP請求給出了匹配的索引... –

+2

好吧...我低估了,因爲這個答案沒有解決這個問題。 – bdares

+1

你的正則表達式也是錯誤的。第一個'(。*)'最初消耗了整個字符串,然後退回足夠遠以使'(\ d +)'匹配一個數字,然後第二個'(。*)'消耗剩下的東西。不是特別有用的結果,我會說。哦,你從結果中離開了「組(3)」。 –

0

距離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}; 
} 
相關問題