Java quote.split 为仅 1 个单词

标签 java split

我正在用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/

相关文章:

java - 登录Facebook App并授权我的应用程序后,如何正确获取Access Token等信息? [安卓]

java - 我的 while 循环第二次显示两个打印时遇到问题

java - Hibernate:如何在Hibernate中删除多行?

php - 使用 PHP 和 Javascript 从 MySQL 拆分数据在 IE 中有效,但在 FF 中无效

string - VBA - 使用 startPOS 和 endPOS 拆分字符串函数

R:如何更改 data.table 列表的项目(或对象)名称?

objective-c - 如何从 Objective-C 中的 char 指针拆分换行符?

php - 使用 PHP 拆分 URL

java - Java 中的 CSV 自动检测

java - 有没有更好的方法来检查字符串中是否有数字?