[英]How to get keywords from a specific index in Java
Suppose I have a string: 假设我有一个字符串:
String advise = "eat healthy food";
In the string I only know the keyword “healthy”. 在字符串中我只知道关键字“健康”。 I don't know what has before the word nor what has after the word.
我不知道这个词之前有什么,也不知道之后的是什么。 I just only know the middle word.
我只知道中间词。 So how can I get the before (“eat”) and after (“food”) keyword of “healthy”?
那么我怎样才能获得“健康”的之前(“吃”)和之后(“食物”)关键词?
Note: Here the middle word's size is always specfic but the other two word's size is always different. 注意:这里中间词的大小总是特定的,但另外两个词的大小总是不同的。 Here “eat” and “food” have been used as an example only.
这里仅以“吃”和“食物”为例。 These two words may be anything anytime.
这两个词可能随时都有。
I need to get these two words into two different strings, not in the same string. 我需要将这两个单词分成两个不同的字符串,而不是在同一个字符串中。
Just split the string: 只需拆分字符串:
advise.split("healthy");
The first value in the array will be "eat", the second will be "food". 数组中的第一个值是“吃”,第二个值是“食物”。
Here is a more general purpose solution that will handle more complex strings. 这是一个更通用的解决方案,可以处理更复杂的字符串。
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.");
}
}
Outputs: 输出:
eat
吃
food
餐饮
I think you can use split and get all the words separately as you wanted. 我认为您可以使用拆分并根据需要单独获取所有单词。
String advise = "eat healthy food";
String[] words = advise.split("healthy");
List<String> word = Arrays.asList(words);
word.forEach(w-> System.out.println(w.trim()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.