64
A
回答
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};
}
相關問題
- 1. 使用正則表達式從此字符串獲取字符串模式
- 2. 正則表達式 - 獲取字符串
- 3. 正則表達式引用字符串
- 4. 字符串模式,正則表達式
- 5. 使用正則表達式中的正則表達式提取子字符串
- 6. 用捕獲的正則表達式模式替換字符串
- 7. 使用正則表達式從字符串中獲取子
- 8. 正則表達式獲取包含引號的字符串
- 9. 正則表達式 - 使用正則表達式在另一個字符串中搜索特定的字符串
- 10. 正則表達式檢索字符串
- 11. 正則表達式檢索字符串
- 12. 正則表達式搜索字符串?
- 13. 正則表達式模式字符串使用標識符
- 14. 使用正則表達式獲取較大字符串中的子字符串
- 15. 使用正則表達式獲取字符串的一部分
- 16. 使用字符串獲取值的正則表達式
- 17. 字符串使用正則表達式替換正則表達式字符類
- 18. PHP的preg_match正則表達式的字符串捕獲模式
- 19. 正則表達式拆分引用的搜索字符串
- 20. 正則表達式獲取字符串從字符串
- 21. 正則表達式檢索字符串中的字符串
- 22. 使用Perl正則表達式的字符串模式匹配
- 23. 正則表達式來捕獲此模式中的單引號字符串...?
- 24. 正則表達式的正則表達式的Java字符串
- 25. Perl追加正則表達式到搜索字符串模式
- 26. 使用正則表達式從字符串中獲取子字符串
- 27. 正則表達式提取字符串
- 28. 正則表達式提取字符串
- 29. 正則表達式提取字符串
- 30. 正則表達式提取字符串
http://docs.oracle.com/javase/6 /docs/api/java/util/regex/Matcher.html –