您可以使用以下正则表达式(([\w/]+):\s?(\d+)),?
来匹配key:value
字符串中的所有内容,然后只需提取GOALS
withgroup(2)
和3
with 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"));