2011-05-31 183 views
2

從字符串[foo](bar)我想提取foobar部分:幫助,正則表達式

Pattern p = Pattern.compile("\\[(.*)\\]\\((.*)\\)"); 
String input = "[foo](bar)"; 
assert p.matcher(input).matches(); 
String[] a = ??? // should be initialized to {"foo", "bar"} 

我怎麼在第四行寫獲得來自輸入foobar

+0

您應該使用p.matcher(輸入),返回你[匹配](http://download.oracle。 com/javase/7/docs/api/java/util/regex/Matcher.html)對象,其中包含您的匹配項。然後,您可以使用find()來查找字符串中的下一個字符串,並使用group()來訪問最後找到的字符串。 – 2011-05-31 18:58:18

回答

4

這應該讓你接近的地方,你想成爲:

Pattern p = Pattern.compile("\\[(.*)\\]\\((.*)\\)"); 
String input = "[foo](bar)"; 
Matcher m = p.matcher(input); 
if (m.find()){ 
    String[] a = { m.group(1), m.group(2) }; 
} 

本質上講,你將創建一個Matcher。然後使用find()找到匹配項。然後,您將使用這些組來查找在括號內匹配的內容。

+0

爲什麼正則表達式組數從1!?但是:+1 – 2011-05-31 19:02:40

+1

@Martijn,因爲組0將持有整個比賽。 – 2011-05-31 19:03:31

0

我會說像下方的正則表達式是比較容易處理和擴展:

[\[\(](.*?)[\]\)] 
+0

但是這只是匹配字符串的一部分,它也匹配無效的部分,比如'(foo)' – 2011-05-31 19:30:22

+0

@Bart Kiers-我知道你是對的,但我仍然想說OP要求提取foo和bar。 – manojlds 2011-05-31 19:31:43