2013-06-03 217 views
0

我有下面的代碼java的正則表達式不包括字符串包含括號

Pattern p = Pattern.compile("^get.*\\("); 
Matcher m = p.matcher("getFieldAsDouble(String)"); 
if (m.find()) { 
    System.out.println(m.group()); 
} 

它返回getFieldAsDouble(

我如何獲得唯一的方法,而不是(的文本名稱?

回答

1

您可以使用正則表達式捕獲組

Pattern p = Pattern.compile("(^get.*)\\("); // The() creates a capture group 
Matcher m = p.matcher("getFieldAsDouble(String)"); 
if (m.find()) { 
    System.out.println(m.group(1)); //Group 1 
} 
+1

打我吧... –

1

你必須附上你的東西在括號匹配,你只是得到全場比賽回來

Pattern p = Pattern.compile("^(get.*)\\("); 

然後,你必須因爲第一個是完整的匹配

m.group(1) 
3

而不是.*使用[^(]*,這將讓任何數目的字符不屬於(

Pattern p = Pattern.compile("^get[^(]*"); 
+0

解釋如何解決什麼比賽,我的回答解釋了怎樣用括號 –

1

你需要圍繞你想用括號什麼,然後得到該組:

Pattern p = Pattern.compile("^(get.*)\\("); 
Matcher m = p.matcher("getFieldAsDouble(String)"); 

if (m.matches()) { 
    System.out.println(m.group(1)); // Group 0 is the whole match 
} 
+0

@vidit打敗你子匹配(我也是)。 –

1

下面是如何在一個簡單的行做到這一點:

String methodName = str.replaceAll("\\(.*", ""); 

這是一個測試:

System.out.println("getFieldAsDouble(String)".replaceAll("\\(.*", "")); 

輸出:

getFieldAsDouble 
+0

不會爲不同的輸入做同樣的事情 –

+0

@JuanMendes是的。我已經添加了可以自己測試的可執行代碼。順便提一句,這直接回答了這個問題。絕對不需要捕獲組或解析行,或者做任何比這更復雜的事情。 – Bohemian

相關問題