Java比较两个带有占位符值的字符串 [英] Java Comparing two strings with placeholder values

查看:39
本文介绍了Java比较两个带有占位符值的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on a command based feature for a project in Java and am having trouble when introducing arguments to these commands.

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

For example all the commands are stored like this this:

"Hey tell [USER] to [ACTION]"

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

Now when the user submits their command it will look like this:

"Hey tell Player to come see me"

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

Now I need to know how I can compare the users inputted command to the stored command containing placeholder values. I need to be able to compare the two strings and recognise that they are the same command and then from this extract the data [USER] and [ACTION] and return them as an array

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

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

Really hope somebody can help me out, thanks

推荐答案

您可以按以下方式使用模式匹配:

You can use Pattern Matching as below:

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

        } 

这篇关于Java比较两个带有占位符值的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆