4

I have a String. The string is "New England 12 Philidelphia 24 (Final)". I need a regaular expression from which i should able to retrieve items like.

  1. First Team -- New England
  2. First Team Score -- 12
  3. Second Team -- Philidelpia
  4. Second Team Score -- 24
  5. Result -- Final or whatever in the braces.
Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
Raghunandan
  • 132,755
  • 26
  • 225
  • 256

3 Answers3

5

Below is a SSCCE showing how to use regex and groups to extract the data you want.

FYI, although it will work for just the input you provided, this code will scan through input containing multiple results like this, matching all of them in the while loop.

public static void main( String[] args ) {
    String input = "New England 12 Philidelphia 24 (Final)";
    String regex = "([a-zA-Z ]+)\\s+(\\d+)\\s+([a-zA-Z ]+)\\s+(\\d+)\\s+\\((\\w+)\\)";
    Matcher matcher = Pattern.compile( regex ).matcher( input);
    while (matcher.find( )) {
        String team1 = matcher.group(1);
        String score1 = matcher.group(2);
        String team2 = matcher.group(3);
        String score2 = matcher.group(4);
        String result = matcher.group(5);
        System.out.println( team1 + " scored " + score1 + ", " + team2 + " scored " + score2 + ", which was " + result);
    }
}

Output

New England scored 12, Philidelphia scored 24, which was Final
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

Use this:

"(\\w+) (\\d+) (\\w+) (\\d+) \((\\w+)\)"
Shiridish
  • 4,942
  • 5
  • 33
  • 64
  • How can it be "tested"? It doesn't even compile! (hint: this is a *java* question) – Bohemian Aug 27 '12 at 05:22
  • Oh my goodness. Dint see that. Sorry, that was in c#, but this regex should work fine. – Shiridish Aug 27 '12 at 05:25
  • I don't have an idea how to extract from the groups in java, so could just give you the regex. Have a look at the solution in [THIS](http://stackoverflow.com/questions/237061/using-regular-expressions-to-extract-a-value-in-java/8116229#8116229) to get an idea in using the above expression for extracting values from groups – Shiridish Aug 27 '12 at 05:43
  • i guess u have to add extra \ like "(\\w+) (\\d+) (\\w+) (\\d+) \\((\\w+)\\)" so that u escape \ in java. – Raghunandan Aug 27 '12 at 05:45
  • yes to escape a `\ or (` we use a \, but do you need to do it in case of `\w` or `\d` as well, as you did? I dont think so! Did that work? – Shiridish Aug 27 '12 at 05:48
  • It din't work. You have to use extra \ to escape backlslah in java. – Raghunandan Aug 27 '12 at 07:17
0

Try this out

^[\D]*\s*\d*\s*[\D]*\s*\d*\s*\([\D]*\)$
Bohemian
  • 412,405
  • 93
  • 575
  • 722
Chris
  • 5,584
  • 9
  • 40
  • 58