如何使用 Java 在正则表达式中检查多个 [args]? [英] How do I check for multiple [args] in a regex with Java?
问题描述
我正在制作一个控制台游戏.. 我希望能够同时检查 2 个人的信息.就我而言,我想制作一个kill checker"命令.命令是
I am making a console game.. and I want to be able to check for 2 people's information at the same time. In my case, I want to make a "kill checker" command. The command is
~killc [username]
使用此命令,我将能够检查 1 人的杀戮次数.如果我想检查 2 个人怎么办?我将如何使用我的 .matches(regex) 来计算 2 个字符串?我试过打字:
With this command, I would be able to check 1 person's kills. What if I want to check 2 people? How would I use my .matches(regex) to figure 2 Strings? I have tried typing:
"^~killc [^ ] [^ ]+$", and "^~killc [^ ] + [a-zA-Z]+$"
但它们不起作用.阅读下面的代码以了解更多信息.
but they don't work. Read my code below for more information.
import java.util.Scanner;
class StackOverflowExample {
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);
}
}
}
推荐答案
您可以将模式与捕获组一起使用,并将捕获组的值拆分为一个空间.
You could use a pattern with a capture group, and split the value of the capture group on a space.
^~killc (\S+(?: \S+)*)$
^
字符串开始~killc\h+
匹配~killc
和 1+ 个空格(
捕获组1\S+(?:\h+\S+)*
匹配 1+ 个非空白字符,并可选择重复 1+ 个空格和 1+ 个非空白字符^
Start of string~killc\h+
Match~killc
and 1+ spaces(
Capture group 1\S+(?:\h+\S+)*
Match 1+ non whitspace chars, and optionally repeat 1+ spaces and 1+ non whitspace chars
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 在正则表达式中检查多个 [args]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!