[英]Java - String can be split with regex but regex match returns 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
应该是。
但是,由于存在另一种情况,比赛尚未进行,所以Team A Team B
。 在这种情况下,两个团队名称由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情况才返回此代码。
我用匹配其自身模式的字符串分别测试了这两个部分,它们工作正常,但是当我像这样组合时却不能。
([\w ]*?)\s+(?:(\d+)-(\d+))?\s+([\w ]*)
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
final String regex = "([\\w ]*?)\\s+(?:(\\d+)-(\\d+))?\\s+([\\w ]*)";
final String[] strings = {"Team A 2-3 Team B", "Team A Team B"};
final Pattern pattern = Pattern.compile(regex);
for (String string : strings) {
Matcher matcher = pattern.matcher(string);
if(matcher.find()) {
System.out.println("Home team: " + matcher.group(1));
if(matcher.group(2) != null) {
System.out.println("Home goal: " + matcher.group(2));
System.out.println("Away goal: " + matcher.group(3));
}
System.out.println("Away team: " + matcher.group(4));
System.out.println("\n");
}
}
}
}
([\\w ]*?)
任意多次捕获集合中的任何字符(单词字符或空格),但次数尽可能少,进入捕获组1 \\s+
匹配一个或多个空格字符 (?:(\\d+)-(\\d+))?
匹配以下零或一次
(\\d+)
一个或多个数字捕获到捕获组2中 -
匹配连字符-
字面上 (\\d+)
一个或多个数字捕获到捕获组3中 \\s+
匹配一个或多个空格字符 ([\\w ]*)
任意多次捕获集合中的任何字符(单词字符或空格)到捕获组4中 如果字符串中间的分数可能不存在,则可以修改表达式以指示:
boolean b = Pattern.matches(" ((\\d+)-(\\d+))? ", input);
...
String[] teamNames = input.split(" ((\\d+)-(\\d+))? ");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.