Java 将两个字符串与占位符值进行比较

Java Comparing two strings with placeholder values

我正在为 Java 中的项目开发基于命令的功能,但在向这些命令引入参数时遇到了问题。

例如所有的命令都是这样存储的:

"Hey tell [USER] to [ACTION]"

现在,当用户提交他们的命令时,它将看起来像这样:

"Hey tell Player to come see me"

现在我需要知道如何将用户输入的命令与包含占位符值的存储命令进行比较。我需要能够比较这两个字符串并识别它们是相同的命令,然后从中提取数据 [USER] 和 [ACTION] 以及 return 它们作为数组

array[0] = "Player"
array[1] = "come see me"

真的希望有人能帮助我,谢谢

您可以使用模式匹配如下:

    String command = "Hey tell [USER] to [ACTION]";
    String input = "Hey tell Player to come see me";
    String[] userInputArray = new String[2];

    String patternTemplate = command.replace("[USER]", "(.*)"); 
    patternTemplate = patternTemplate.replace("[ACTION]", "(.*)");

    Pattern pattern = Pattern.compile(patternTemplate);
    Matcher matcher = pattern.matcher(input);
        if (matcher.matches()) {
            userInputArray[0] = matcher.group(1);
            userInputArray[1] = matcher.group(2);

        } 

如果您不需要像 "Hey tell [USER] to [ACTION]" 这样的存储字符串,您可以使用 Java (java.util.regex) 模式和匹配器。

这是一个例子:

Pattern p = Pattern.compile("Hey tell ([a-zA-z]+) to (.+)");
List<Pattern> listOfCommandPattern = new ArrayList<>();
listOfCommandPattern.add(p);

例子,解析命令:

String user;
String command;
Matcher m;
// for every command
for(Pattern p : listOfCommandPattern){
   m = p.matcher(inputCommand);
   if (m.matches()) {
       user = m.group(1);
       command = m.group(2);
       break; // found user and command
   }
}

这里是一个稍微更通用的版本:

String pattern = "Hey tell [USER] to [ACTION]";
String line = "Hey tell Player to come see me";

/* a regular expression matching bracket expressions */
java.util.regex.Pattern bracket_regexp = Pattern.compile("\[[^]]*\]");

/* how many bracket expressions are in "pattern"? */
int count = bracket_regexp.split(" " + pattern + " ").length - 1;

/* allocate a result array big enough */
String[] result = new String[count];

/* convert "pattern" into a regular expression */
String regex_pattern = bracket_regexp.matcher(pattern).replaceAll("(.*)");
java.util.regex.Pattern line_regex = Pattern.compile(regex_pattern);

/* match "line" */
if (line_regex.matcher(line).matches()) {
    /* extract the matched strings */
    for (int i=0; i<count; ++i) {
        result[i] = line_matcher.group(i+1);
        System.out.println(result[i]);
    }
} else {
    System.out.println("Doesn't match.");
}