2013-02-16 11 views
0

我有限的經驗和正則表達式的知識。我需要做的是將一個字符串分成多個子字符串。使用正則表達式來分割(有限的經驗瓦特/正則表達式)

有問題的字符串是

String str = 
    "Brayden Schenn, C GAMES PLAYED: 13, GOALS: 3, ASSISTS: 6," + 
    " POINTS: 9, PLUS/MINUS: 5, PIM: 7"; 

我想這分裂成子,其他的字符串,即:

String gamesPlayed = "13"; 
String goals = "3"; 
etc 

或類似的東西,所以我可以拉出來很多進球,助攻等如何父的字符串中。

任何幫助,非常感謝。

+0

拆分爲 ''要麼 ':'? – 2013-02-16 07:37:40

+3

正則表達式非常容易學習和瘋狂有用。有網上的文章堆,所以我建議你只有一個谷歌和撿起來。 – TrewTzu 2013-02-16 07:38:11

回答

2

您可以使用下面的正則表達式(([\w/]+):\s?(\d+)),?在你的字符串中所有key:value匹配,然後只需提取GOALSgroup(2)3group(3)

正則表達式讀起來像這樣:

(   # capture key/value (without the comma) 
    (   # capture key (in group 2) 
    [\w/]+ # any word character including/one or more times 
) 
    :   # followed by a colon 
    \s?  # followed by a space (or not) 
    (   # capture value (in group 3) 
    \d+  # one or mor digit 
    ) 
) 
,?   # followed by a comma (or not) 

它應該符合以下考慮您的字符串:

PLAYED: 13 
GOALS: 3 
ASSISTS: 6 
POINTS: 9 
PLUS/MINUS: 5 
PIM: 7 

這裏的Java代碼:

String s = "Brayden Schenn, C GAMES PLAYED: 13, GOALS: 3, ASSISTS: 6, POINTS: 9, PLUS/MINUS: 5, PIM: 7"; 
Matcher m = Pattern.compile("(([\\w/]+):\\s?(\\d+)),?").matcher(s); 
Map<String, Integer> values = new HashMap<String, Integer>(); 
// find them all 
while (m.find()) { 
    values.put(m.group(2), Integer.valueOf(m.group(3))); 
} 
// print the values 
System.out.println("Games Played: " + values.get("PLAYED")); 
System.out.println("Goals: " + values.get("GOALS")); 
System.out.println("Assists: " + values.get("ASSISTS")); 
System.out.println("Points: " + values.get("POINTS")); 
System.out.println("Plus/Minus: " + values.get("PLUS/MINUS")); 
System.out.println("Pim: " + values.get("PIM")); 
3

我會:

  • 使用,
  • 然後先用分割:

劈我已經得到了接近零的Java經驗,但是這就是我建議:

String initialStr = 
    "GAMES PLAYED: 13, GOALS: 3, ASSISTS: 6, POINTS: 9,"+ 
    " PLUS/MINUS: 5, PIM: 7"; 
String colon = ": "; 
Map< String, Integer> keyValuePairs = new HashMap<>();// Java 7 diamond  
String[] parts = initialStr.split(","); 
for(String keyValue : parts) { 
    String[] pair = keyValue.split(colon); 
    keyValuePairs.put(pair[0], Integer.parseInt(pair[1])); 
} 

詢問keyValuePairs如下:

assert keyValuePairs.get("GAMES PLAYED") == 13; 
+0

+1:你甚至不需要使用正則表達式! – nneonneo 2013-02-16 07:45:29

+0

@nneonneo我只是希望在上面沒有語法錯誤(Java真的*不是我的東西...):-) – 2013-02-16 07:46:17

+0

如果可以的話,我會給你另外一個用於跳出你的舒適區的+1;) – nneonneo 2013-02-16 07:52:04