如何使用 Java 检查正则表达式中的多个 [args]?

How do I check for multiple [args] in a regex with Java?

我正在制作主机游戏..我希望能够同时查看 2 个人的信息。就我而言,我想执行“kill checker”命令。命令是

~killc [username]

用这个命令,我可以查看1个人的杀戮。如果我想检查2个人怎么办?我将如何使用我的 .matches(regex) 来计算 2 个字符串?我试过输入:

"^~killc [^ ] [^ ]+$", and "^~killc [^ ] + [a-zA-Z]+$"

但它们不起作用。 阅读下面的代码以获取更多信息。

import java.util.Scanner;
class WhosebugExample {
  static int kills = 10;
  public static void main(String[] args) {
    
    System.out.println("Kill count command: ~killc [username]");
    Scanner userInt = new Scanner(System.in);
    String userInput = userInt.nextLine();
    if (userInput.matches("^~killc [^ ]+$"/**How would I input more than one username?**/)){
      String[] parts = userInput.split(" ");
      String username = parts[1];
      System.out.printf("%s has " + kills + " kills.",username);
      
    }
    
  }
}

重复组怎么样?

^~killc(?: [^ ]+)+$

这将在输入命令时捕获一个或多个用户名。实际上解析它们取决于你,但如果用户名格式正确,这将捕获它们。 就个人而言,我会在 [^ ]+ 周围非常小心,因为它会接受一个换行符作为匹配项;如果可用,请尝试 \S+,它将匹配任何非空格的内容。

您可以使用带有捕获组的模式,并将捕获组的值拆分为 space。

^~killc (\S+(?: \S+)*)$
  • ^ 字符串开头
  • ~killc\h+ 匹配 ~killc 和 1+ spaces
  • ( 捕获 组 1
    • \S+(?:\h+\S+)* 匹配 1+ 个非 whitspace 个字符,并可选择重复 1+ 个 space 和 1+ 个非 whitspace 个字符
  • ) 关闭组 1
  • $ 字符串结束

Regex demo

System.out.println("Kill count command: ~killc [username]");
Scanner userInt = new Scanner(System.in);
String regex = "^~killc\h+(\S+(?:\h+\S+)*)$";
String userInput = userInt.nextLine();

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(userInput);

if (matcher.find()) {
    for (String username : matcher.group(1).split(" "))
        System.out.printf("%s has " + kills + " kills.\n",username);
}

如果输入是~killc test1 test2

输出将是

Kill count command: ~killc [username]
test1 has 10 kills.
test2 has 10 kills.

Java demo