2017-04-19 23 views
0

輸入:獲取的參數的括號內,它在Java中添加到列表

(cl(A, B, 0.620) :- /* #pos=1,513 * 

預期輸出:

Fetch and Add A and B to a list 

碼(嘗試1):

Matcher m2 = Pattern.compile("\\((.*?)\\)").matcher(inputString); 
      while(m2.find()) 
       { 
       System.out.println(m2.group(1)); 
       } 

輸出:

cl(A, B, 0.620 

代碼嘗試2:

System.out.println(inputString.substring(inputString.indexOf("(")+1,inputString.indexOf(")"))); 

仍然得到相同的輸出。

請告訴我什麼是錯誤。

+1

你能解釋一下嗎? –

+0

你從第一個打開的括號與第一個閉括號相匹配 - 你(似乎)需要實際解析字符串來匹配開括號和右括號 – UnholySheep

+0

@MaulikDoshi用​​例是獲取palenthesis中的參數。 –

回答

2

與您當前嘗試的主要問題是,你的模式是錯誤的:

\\((.*?)\\) 

此相匹配的左括號,接着右括號。請注意,模式中的捕獲組不計數;這些括號不會被匹配。相反,使用以下模式:

\\(.*?\\((.*?)\\) 

全碼:

String inputString = "(cl(A, B, 0.620) :- /* #pos=1,513 *"; 
List<String> list = new ArrayList<>(); 
Matcher m2 = Pattern.compile("\\(.*?\\((.*?)\\)").matcher(inputString); 
if (m2.find()) { 
    String match = m2.group(1); 
    String[] parts = match.split(",\\s+"); 
    for (String part : parts) { 
     list.add(part); 
     System.out.println("Found an item: " + part); 
    } 
} 

輸出:

Found an item: A 
Found an item: B 
Found an item: 0.620 

演示在這裏:

Rextester