2014-12-11 81 views
0

我有以下java代碼。分類標準級解析

List<String> resultList = new ArrayList<String>();  
String taxonomyLevels = "(subject:\"Chemistry\" OR (course:\"Organic Chemistry\" OR course:\"Inorganic Chemistry\" OR (unit:\"unit1\")))"; 

在這裏,主題,課程和單位是分類學的水平。雙引號中的值是每個級別的值。我想要組合的所有分類水平

我想要這個被解析並返回resultList。返回列表應具有以下值,

"subject:\"Chemistry\"" 
"subject:\"Chemistry\"&course:\"Organic Chemistry\"" 
"subject:\"Chemistry\"&course:\"Inorganic Chemistry\"" 
"subject:\"Chemistry\"&course:\"Inorganic Chemistry\"&unit:\"unit1\"" 

更新 - 啓動

對於下面輸入,

taxonomyLevels = "(subject:\"something1\" OR (course:\"somethingElse\" OR (unit:\"abcd test\" OR unit:\"efgh\") OR course:\"c2\" OR (unit:\"u2\")))"; 

輸出列表應該是,

"subject:\"Chemistry\"" 
"subject:\"Chemistry\"&course:\"Organic Chemistry\"" 
"subject:\"Chemistry\"&course:\"Organic Chemistry\"&unit:\"unit2\"" 
"subject:\"Chemistry\"&course:\"Organic Chemistry\"&unit:\"unit3\"" 
"subject:\"Chemistry\"&course:\"Inorganic Chemistry\"" 
"subject:\"Chemistry\"&course:\"Inorganic Chemistry\"&unit:\"unit1\"" 

這是分類法層次的組合。換句話說,需要學科,課程和單元的組合。

這是一種樹狀結構。每個Open括號都會創建一個新的子級別。兩個相同等級之間的創建新的兄弟姐妹。

更新 - 完

我已經嘗試了多種方法就像把一個級別的時間和得到下一個元素,並與現有的字符串添加,但未能拿出一個解決方案。

請幫忙。提前致謝。

+0

你有太多的引號我不知道你想用這個String來做什麼,但是你需要首先刪除所有額外的標記,否則你只會得到大量的編譯器錯誤String level =「(subject:\ Chemistry \ OR(course:\ Organic Chemistry \ OR course:\ Inorganic Chemistry \ OR(unit:\ unit1 \)))」; – 2014-12-11 04:23:42

+0

@DavidColer。我已經更新了這個問題。我需要雙引號,因爲如果主題具有** A或B **的值,可能會引起混淆。而且,由於雙引號解析正確,因此不會出現編譯錯誤。 – KarthiK 2014-12-11 05:00:57

回答

0
private ArrayList<String> resultList = new ArrayList<String>();  
private String taxonomyLevels = "(subject:\"Chemistry\" OR (course:\"Organic Chemistry\" OR course:\"Inorganic Chemistry\" OR (unit:\"unit1\")))"; 

public ArrayList<String> parse() { 
    String[] temp = taxonomyLevels.split(" OR "); 
    String[] clean = new String[temp.length]; 
    for(int i = 0; i<temp.length;i++){ 
     clean[i] = cleanUp(temp[i]); 
    } 
    resultList.add(clean[0]); 
    resultList.add(clean[0]+"&"+clean[1]); 
    resultList.add(clean[0]+"&"+clean[2]); 
    resultList.add(clean[0]+"&"+clean[2]+"&"+clean[3]); 
    return resultList; 
} 

private String cleanUp(String s){ 
    char[] chars = s.toCharArray(); 
    StringBuilder sb = new StringBuilder(); 
    for(char c:chars){ 
     if(c!='(' && c!=')')sb.append(c); 
    } 
    return sb.toString(); 
} 

這是你正在嘗試做什麼?

+0

我很欣賞你的嘗試。但是,它不會給出關卡的組合。請檢查我的問題更新。 – KarthiK 2014-12-12 09:33:41