可以使用正则表达式拆分Java字符串,但正则表达式匹配返回false
我尝试拆分以下字符串,示例如下:
Team A 2-3 Team B
这是一个字符串,球队的名字在2个方面,他们之间的得分在中间。我需要分别获得球队的名字和分数。这是我到目前为止针对这一部分的代码:
String homeTeam;
String awayTeam;
int homeGoal = 0;
int awayGoal = 0;
String input = "Team A 2-3 Team B";
Scanner s = new Scanner(input).useDelimiter("-");
String[] teamNames = input.split(" (\\d+)-(\\d+) ");
homeTeam = teamNames[0];
awayTeam = teamNames[1];
for(int i = 0; i < teamNames.length; i++) {
System.out.println(teamNames[i]);
}
s.findInLine("(\\d+)-(\\d+)");
MatchResult result = s.match();
for (int i=1; i<=result.groupCount(); i++)
System.out.println(result.group(i));
s.close();
此文件的输出:
Team A
Team B
2
3
应该如此
但是,由于还有另一种情况,比赛尚未开始。本例中的2个团队名称由2个空格分隔。上面使用的正则表达式不再有效,因此我有两个案例。这是我的总体代码:
String homeTeam;
String awayTeam;
int homeGoal = 0;
int awayGoal = 0;
String input = "Team A 2-3 Team B";
Scanner s = new Scanner(input).useDelimiter("-");
boolean b = Pattern.matches(" (\\d+)-(\\d+) ", input);
if (b){
String[] teamNames = input.split(" (\\d+)-(\\d+) ");
homeTeam = teamNames[0];
awayTeam = teamNames[1];
for(int i = 0; i < teamNames.length; i++) {
System.out.println(teamNames[i]);
}
s.findInLine("(\\d+)-(\\d+)");
MatchResult result = s.match();
for (int i=1; i<=result.groupCount(); i++)
System.out.println(result.group(i));
s.close();
} else {
String[] teamNames = input.split(" ");
homeTeam = teamNames[0];
awayTeam = teamNames[1];
for(int i = 0; i < teamNames.length; i++) {
System.out.println(teamNames[i]);
}
}
System.out.println(b);
我遇到的问题是,即使对于字符串,b也返回false
Team A 2-3 Team B
因此,只有else案例与此代码一起返回
我用符合它们自己模式的字符串分别测试了这两个部分,它们工作得很好,但当我这样组合时就不行了
# 1 楼答案
如果字符串中间的分数可能不存在,则可以修改表达式以表示:
# 2 楼答案
代码
See regex in use here
代码
See code in use here
解释
([\w ]*?)
将集合中的任何字符(单词字符或空格)捕获任意次数(但尽可能少)到捕获组1中\s+
匹配一个或多个空白字符(?:(\d+)-(\d+))?
匹配以下零或一次(\d+)
将一个或多个数字捕获到捕获组2中-
按字面意思匹配连字符-
(\d+)
将一个或多个数字捕获到捕获组3中\s+
匹配一个或多个空白字符([\w ]*)
多次将集合中的任何字符(单词字符或空格)捕获到捕获组4中