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.
5
  • 3
    Will you need to parse "Hannover 96 2 Schalke 04 1 (Final)"? Commented Aug 27, 2012 at 5:10
  • 1
    "Hannover 96 Schalke 04 (Final)" Something like this. But not the extra 2 and 1 after the scores. Commented Aug 27, 2012 at 5:12
  • 1
    My point exactly. The extra 2 and 1 is the score. Commented Aug 27, 2012 at 5:13
  • @Thilo not even mentioning München 1860 :D Commented Aug 27, 2012 at 5:14
  • Or 1. FC Saarbruecken, to put the digits in front. Commented Aug 27, 2012 at 5:15

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

0

Try this out

^[\D]*\s*\d*\s*[\D]*\s*\d*\s*\([\D]*\)$

Comments

0

Use this:

"(\\w+) (\\d+) (\\w+) (\\d+) \((\\w+)\)"

6 Comments

How can it be "tested"? It doesn't even compile! (hint: this is a java question)
Oh my goodness. Dint see that. Sorry, that was in c#, but this regex should work fine.
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 to get an idea in using the above expression for extracting values from groups
i guess u have to add extra \ like "(\\w+) (\\d+) (\\w+) (\\d+) \((\\w+)\)" so that u escape \ in java.
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?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.