Regular expression in java for string parsing

I have a String. Line - "New England 12 Philadelphia 24 (Final)". I need a regaular expression from which I could get elements like.

  • First Team - New England
  • Team first score - 12
  • Second Team - Philadelphia
  • Second team - 24
  • The result is the finale or something else in braces.
+4
source share
3 answers

The following is an SSCCE that shows how to use regex and groups to extract the necessary data.

FYI, although it will only work for the input you provided, this code will scan through input containing several results like this, matching them all in a while .

 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 
+5
source

Use this:

 "(\\w+) (\\d+) (\\w+) (\\d+) \((\\w+)\)" 
0
source

try it

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

All Articles