2009-08-23 39 views
3

我嘗試使用正則表達式解析字符串以從中獲取參數。 作爲一個例子:使用正則表達式的Java Stringparsing

 
String: "TestStringpart1 with second test part2" 
Result should be: String[] {"part1", "part2"} 
Regexp: "TestString(.*?) with second test (.*?)" 

我Testcode是:

 
String regexp = "TestString(.*?) with second test (.*?)"; 
String res = "TestStringpart1 with second test part2"; 

Pattern pattern = Pattern.compile(regexp); 
Matcher matcher = pattern.matcher(res); 
int i = 0; 
while(matcher.find()) { 
    i++; 
    System.out.println(matcher.group(i)); 
} 

但只輸出 「第一部分」 可能有人給我暗示?

感謝

+0

您可以使用以下網站來檢查您正則表達式對測試用例:https://regex101.com/ – luizfzs 2017-05-26 19:52:29

回答

2

可能會有一些固定的正則表達式

String regexp = "TestString(.*?) with second test (.*)"; 

和更改的println代碼..

if (matcher.find()) 
    for (int i = 1; i <= matcher.groupCount(); ++i) 
     System.out.println(matcher.group(i)); 
+0

感謝,這是它。 – mknjc 2009-08-23 09:36:00

1

嗯,你永遠只能要求它...在你的原代碼,發現繼續將匹配器從的整個正則表達式中的匹配移動到下一個匹配器,而在這段時間內,您只能拉出一個組。實際上,如果你的字符串中有多個匹配的正則表達式,你會發現對於第一次出現,你會得到「part1」,第二次出現你會得到「part2」,並且對於任何其他的參考你會得到一個錯誤。

while(matcher.find()) { 

    System.out.print("Part 1: "); 
    System.out.println(matcher.group(1)); 

    System.out.print("Part 2: "); 
    System.out.println(matcher.group(2)); 

    System.out.print("Entire match: "); 
    System.out.println(matcher.group(0)); 
}