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.
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
用这个:
"(\\w+) (\\d+) (\\w+) (\\d+) \((\\w+)\)"
试试看
^[\D]*\s*\d*\s*[\D]*\s*\d*\s*\([\D]*\)$
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.