有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

可以使用正则表达式拆分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案例与此代码一起返回

我用符合它们自己模式的字符串分别测试了这两个部分,它们工作得很好,但当我这样组合时就不行了


共 (2) 个答案

  1. # 1 楼答案

    如果字符串中间的分数可能不存在,则可以修改表达式以表示:

        boolean b = Pattern.matches(" ((\\d+)-(\\d+))? ", input);
        ...
        String[] teamNames = input.split(" ((\\d+)-(\\d+))? ");
    
  2. # 2 楼答案

    代码

    See regex in use here

    ([\w ]*?)\s+(?:(\d+)-(\d+))?\s+([\w ]*)
    

    代码

    See code in use here

    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中