2017-07-18 138 views
-3

我在說的是,我試圖做一個方法來篩選出基於正則表達式的字符串數組,但我無法實現這一點。例如,我有一個數組用於java字符串匹配的正則表達式「number(number)」。

String[] items = ["6652(1).png", "7876(2).png", "7890-(1).jpg", "6543(1).JPG", "12249(3)-.PNG"] 

public ArrayList<String> filterByRegularExpress(String[] items) { 
    ArrayList<String> filteredStrings = new ArrayList<String>(); 
    for(String item: items) { 
     if(item.contains("regularexpression")){ // it is in here, i need to do some regular express for number(number). 
      filteredStrings.add(item); 
     } 
    } 
    System.out.print(filteredStrings); 
} 

這樣的結果將是"6652(1).png" , "7876(2).png" , "6543(1).JPG"

我怎樣寫這樣的正則表達式? 感謝您的幫助。

+1

嗯,也許檢查正則表達式的各種在線教程之一,然後用各種可用的在線正則表達式工具之一檢查您所創建的表達。 – JacksOnF1re

+0

爲什麼你不能實現this_? – Flown

+0

順便說一下..contains比較字符串。所以如果找到一個子字符串,那麼在要調用的字符串內部就包含了。如果您想查看正則表達式是否與「匹配」相比,請使用string.matches(regEx)。 – JacksOnF1re

回答

0

您可以用圖案

Pattern p = Pattern.compile("\\d+"); 
Matcher m = p.matcher("There are more than -2 and less than 12 numbers here"); 
while (m.find()) { 
    System.out.println(m.group()); 
} 

按照Java正則表達式做吧,+表示「一次或多次」和\ d的意思是「數字」。

注:「雙反斜線」是一個轉義序列,以得到一個反斜槓 - 因此,在Java字符串\ d爲您提供了實際的結果:\ d

+0

我喜歡使用Pattern和Matcher的方法,而不是string.matches(),以便在每次迭代中都不會創建一個模式。此外,不需要查找和組。如果m.matches == true,則可以將該字符串添加到結果列表中。 – JacksOnF1re

1

試試這個你方法的主體:

ArrayList<String> filteredStrings = new ArrayList<String>(); 
Pattern pat = Pattern.compile("\\A\\d+\\(\\d+\\)\\..+\\z"); 
for(String item: items) { 
    Matcher matcher = pat.matcher(item); 
    if(matcher.matches()){ // it is in here, i need to do some regular express for number(number). 
     filteredStrings.add(item); 
    } 
} 
System.out.print(filteredStrings); 

這將匹配基於輸入(\\A)的開始的字符串,然後通過任何數量的數字(至少一個,雖然,\\d+),隨後其被轉義,因爲它字面開括號在正則表達式(\\()中有特殊含義,那麼brac之間的任何數字(如果這隻能在你的場景中只有一位數字,只需刪除+),然後右括號再次像開場一樣逃脫,然後是一個字面值,因爲其特殊含義而逃脫。在正則表達式(\\.),然後我們用的是特殊的意義,這意味着「任何字符」,和我們說可以有任意數量的這裏的任何字符(.+),其次是字符串(\\z)的結局。因此,總而言之,以更易讀的方式,這與number(number).anything匹配。在你的例子中,我測試了它並得到了正確的輸出[6652(1).png, 7876(2).png, 6543(1).JPG]