Java使用占位符值比较两个字符串

时间:2016-06-22 08:47:29

标签: java string command

我正在为Java项目开发一个基于命令的功能,并且在为这些命令引入参数时遇到了麻烦。

例如,所有命令都存储如下:

"Hey tell [USER] to [ACTION]"

现在,当用户提交命令时,它将如下所示:

"Hey tell Player to come see me"

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

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

真的希望有人可以帮助我,谢谢

3 个答案:

答案 0 :(得分:0)

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

    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);

        } 

答案 1 :(得分:0)

如果您不需要存储的字符串,例如“嘿告诉[USER]到[ACTION]”,您可以使用Java(java.util.regex)Pattern和Matcher。

这是一个例子:

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
   }
}

答案 2 :(得分:0)

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

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.");
}