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

或类似的东西,这样我就可以找出父字符串中有多少个进球、助攻等。

任何帮助深表感谢。

4

2 回答 2

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;
于 2013-02-16T07:44:08.403 回答
2

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