[英]Java Comparing two strings with placeholder values
我正在為Java項目開發一個基於命令的功能,並且在為這些命令引入參數時遇到了麻煩。
例如,所有命令都存儲如下:
"Hey tell [USER] to [ACTION]"
現在,當用戶提交命令時,它將如下所示:
"Hey tell Player to come see me"
現在我需要知道如何將用戶輸入的命令與包含占位符值的存儲命令進行比較。 我需要能夠比較兩個字符串並識別它們是相同的命令,然后從中提取數據[USER]和[ACTION]並將它們作為數組返回
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和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
}
}
這是一個稍微更通用的版本:
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.");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.