我正在用java创建一个程序,它可以为你做各种各样的事情,比如打开程序。 我想知道是否可以使用 .split 函数只记住必须拆分的部分之后的 1 个单词。
这就是现在的工作方式;
User: Can you open chrome? (this is where the program looks for the word 'open' and saves all that comes after it)
Program: Sure, I'll open chrome for you. (chrome opens)
现在,我希望它只记住“打开”一词之后的第一个单词。 这可能吗? 如果是这样,最好的方法是什么?
最佳答案
在open
之后使用正则表达式获取字符串可能是最灵活的方法:
public static void main(String args[]) {
String line = "Will you open chrome?";
//will get everything after open, including punctuation like the question mark.
//You need to modify the regex if that's not what you want.
String pattern = "open (.*)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find()) {
System.out.println("Value after open is: " + m.group(1));
} else {
System.out.println("NO MATCH");
}
}
返回:打开后值为:chrome?
如果您不需要问号,请更新正则表达式以从匹配组中排除问号:
String pattern = "open (.*)\\?";
关于Java quote.split 为仅 1 个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22425637/