我有一个字符串。该字符串是“New England 12 Philidelphia 24(Final)”。我需要一个regaular表达式,我可以从中检索像。
这样的项目答案 0 :(得分:5)
下面是一个SSCCE,展示了如何使用正则表达式和组来提取所需的数据。
仅供参考,虽然它只适用于您提供的输入,但此代码将扫描包含多个结果的输入,并在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);
}
}
输出
New England scored 12, Philidelphia scored 24, which was Final
答案 1 :(得分:0)
使用此:
"(\\w+) (\\d+) (\\w+) (\\d+) \((\\w+)\)"
答案 2 :(得分:0)
试试这个
^[\D]*\s*\d*\s*[\D]*\s*\d*\s*\([\D]*\)$