代码之家  ›  专栏  ›  技术社区  ›  user6363583

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

  •  1
  • user6363583  · 技术社区  · 10 年前

    假设我有一个字符串:

    String advise = "eat healthy food";
    

    在字符串中,我只知道关键字health。我不知道单词前有什么,单词后有什么。我只知道中间的单词。那么我怎样才能得到健康的before(eat)和after(food)关键字呢?

    注意:这里中间的单词大小总是特定的,但其他两个单词的大小总是不同的。这里的食物和食物仅用作示例。这两个词随时都可能出现。

    我需要把这两个单词分成两个不同的字符串,而不是同一个字符串。

    3 回复  |  直到 10 年前
        1
  •  0
  •   Robert Moskal    10 年前

    只需拆分字符串:

    advise.split("healthy");
    

    数组中的第一个值将是“eat”,第二个值是“food”。

        2
  •  0
  •   Community Mohan Dere    6 年前

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

    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.");
        }
    }
    

    输出:

    吃

    食物

        3
  •  0
  •   Seek Addo    10 年前

    我想你可以使用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()));