您可以使用下面的正則表達式(([\w/]+):\s?(\d+)),?
在你的字符串中所有key:value
匹配,然後只需提取GOALS
與group(2)
和3
與group(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"));
拆分爲 ''要麼 ':'? – 2013-02-16 07:37:40
正則表達式非常容易學習和瘋狂有用。有網上的文章堆,所以我建議你只有一個谷歌和撿起來。 – TrewTzu 2013-02-16 07:38:11