我正在用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”之后的第一个单词。
这可能吗?
如果是这样,最好的方法是什么?
最佳答案
使用正则表达式在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");
}
}
返回值:
Value after open is: chrome?
如果您不想要问号,请更新正则表达式以从匹配组中排除问号:
String pattern = "open (.*)\\?";