2014-12-26 33 views

回答

1

包含ArrayList的方法通過調用字符串equals方法,因此你不能用contains方法檢查精確的字符串匹配。相反,你可以使用字符串startsWith方法,通過遍歷列表,這樣做:爲全文

for (String str : stringList) { 
    if (str.startsWith("abc/xyz")) {//here even you could use contains if you want to find for your pattern anywhere within string. 
     System.out.println("I found the string"); 
     break; 
    } 
} 
+0

元件'dfd/abc/xyz/*'失敗。否則,沒關係。 –

+0

@sᴜʀᴇsʜᴀᴛᴛᴀ謝謝。我添加了一個註釋,要使用包含如果OP要在中間字符串匹配 – SMA

+0

這可能做同樣的沒有迭代? – Prabhu

0

包含只適用於全文它返回true。你應該嘗試String's indexOf()方法。在列表中循環並嘗試

for (String element: list) { 
    if(element.indexOf("abc/xyz")>0){ 
    return true; 
    } 
} 
0

indexOf可以在這種情況下提供幫助。除此之外,matches()也可以提供幫助。

for (String elem : lst) { 
    if (elem.matches("abc/xyz.*")) 
    return true; 
} 
0

contains()方法檢查,而不是正則表達式,你可以使用的indexOf或模式API,以配合正則表達式或考慮其他API,如GUAVAApache common utils

List<String> getStrings(List<String> list, String regex) { 

     List<String> result = new ArrayList<String>(); 

     Pattern p = Pattern.compile(regex); 

     for (String str:list) { 
     if (p.matcher(str).matches()) { 
      result.add(str); 
     } 
     } 

     return result 
    }