如何从 Java 中的特定索引获取关键字

How to get keywords from a specific index in Java

假设我有一个字符串:

String advise = "eat healthy food";

字符串中我只知道关键字“healthy”。我不知道这个词之前有什么,也不知道这个词之后有什么。我只知道中间的词。那么如何获取“healthy”的before(“eat”)和after(“food”)关键词呢?

注意:这里中间单词的大小总是特定的,而另外两个单词的大小总是不同的。这里“吃”和“食物”仅用作示例。这两个词随时可能是任何东西。

我需要将这两个词放入两个不同的字符串中,而不是在同一个字符串中。

只是拆分字符串:

advise.split("healthy");

数组中的第一个值为 "eat",第二个值为 "food"。

这是一个更通用的解决方案,可以处理更复杂的字符串。

public static void main (String[] args)
{
    String keyword = "healthy";

    String advise = "I want to eat healthy food today";

    Pattern p = Pattern.compile("([\s]?+[\w]+[\s]+)" + keyword + "([\s]+[\w]+[\s]?+)");
    Matcher m = p.matcher(advise);

    if (m.find())
    {
        String before = m.group(1).trim();
        String after = m.group(2).trim();

        System.out.println(before);
        System.out.println(after);
    }
    else
    {
        System.out.println("The keyword was not found.");
    }
}

输出:

eat

food

我觉得你可以用split把所有的词分开,你想要的。

String advise = "eat healthy food";
String[] words = advise.split("healthy");
List<String> word = Arrays.asList(words);
word.forEach(w-> System.out.println(w.trim()));