MaxK
MaxK

Reputation: 437

Using regex to split (limited experience w/ regex)

I have limited experience and knowledge of regex. What I need to do is split a string into multiple substrings.

The string in question is

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

I want to split this up into substrings, other strings, ie.

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

or something like that so I can pull out how many goals, assists, etc. are in the parent string.

Any help is much appreciated.

Upvotes: 0

Views: 196

Answers (2)

Dr.Kameleon
Dr.Kameleon

Reputation: 22810

What I would :

  • First split using ,
  • Then split using :

I've got close to zero experience in Java but that's what I'd suggest :

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] ));
}

Ask keyValuePairs as follow :

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

Upvotes: 3

Alex
Alex

Reputation: 25613

You could use the following regular expression (([\w/]+):\s?(\d+)),? to match all the key:value in your String, and then just extract GOALS with group(2) and 3 with group(3).

The regular expression reads like this:

(            # 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)

It should match the following considering your String:

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

Here's the Java code:

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"));

Upvotes: 2

Related Questions