2014-01-17 46 views
1

我想提取多個括號之間的字符串,但它也應該沒有任何括號。這是我現在得到提取可選括號之間的字符串

Pattern pw = Pattern.compile("\\(?(.*)\\)?\\^\\(?(.*)\\)?"); 
    Matcher m = pw.matcher("2+1^(3+4)"); 
    if(m.find()){ 
     System.out.println(m.group(1)); 
     System.out.println(m.group(2)); 
    }" 

此打印:

2+1 
3+4) 

而應該是:

2+1 
3+4 

任何幫助表示讚賞!

回答

0

嘗試使它非貪婪使用:

.*? 

,而不是.*

你的正則表達式:

Pattern pw = Pattern.compile("\\(?(.*?)\\)?\\^\\(?(.*?)\\)?"); 
相關問題