2013-03-04 59 views
0

簡單的問題 - 可能 - 但我沒有找到解決方法沒有解決方法。Java分析值直到行尾

我想解析某事。像

1) item1;; item3 
2) item1;item2; 
3) ; item2; 
4) ;; 
... 

我有一個相匹配,並返回給定索引的所有項目的StringList匹配功能:

public static List<String> getAllMatchings(String input, String reg, int groupIndex) { 
    Pattern pattern = Pattern.compile(reg);  
    Matcher matcher = pattern.matcher(input); 

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

    while (matcher.find()) { 
     if (groupIndex <= matcher.groupCount()) { 
      ls.add(matcher.group(groupIndex)); 
     } 
    } 

    return ls; 
} 

現在,有這樣的行,我想有一個像{「ITEM1一個StringList的「,」item2「,」item3「}。但我得到的 - 用我的解決方案 - { 「物品1」, 「ITEM2」, 「項目3」, 「」}:

List<String> strList = getAllMatchings(line, "([^;]*)(;|\\z)",1); 

就這樣,我必須做出一個醜陋的解決方法:

strList.remove(strList.size()-1); 

不太好。但是我沒有找到解決這個問題的辦法。有人能幫我嗎?

加法:順便說一下。有這種解決方法不起作用的情況。情況4)給我只有2個空元素。

回答

0

只能添加,如果他們不爲空項:

String item = matcher.group(groupIndex).trim(); 
if (!item.isEmpty()) { 
    ls.add(item); 
} 
+0

Sry,有一個問題。如「item1 ;; item3」,導致項目可能爲空。我改變了我的問題一點,因爲我沒有提到 – 2013-03-04 13:20:58

1

爲什麼不直接劈在分號?

UPDATE:算上分號,以確保元素的權數

int count = StringUtils.countMatches("item1;item2;;;;", ";"); 
String[] values = input.split(";",count); 

(需要Commons Lang

+1

因爲我想靈活地爲匹配元素設置更具體的模式 – 2013-03-04 13:01:59

+0

String.split接受正則表達式,因此它可能適合您的使用。除非需要將邏輯添加到提取中,否則我會推薦這一點。 – antonyh 2013-03-04 13:05:05

+0

以下情況如何? String row =「item1 ;;;」 String [] b = a.split(「;」)。有副作用的結果。 :/我需要一個四元素數組。 – 2013-03-04 13:12:26

0

如果報價是不是你的字符串的一部分,你可以使用split方法的字符串:

String input = "item1; item2; item3"; 
List<String> list = Arrays.asList(input.split("; "); 
0

您可以過濾空字符串或matcher.start/end是否相等。