java如何验证字符串中是否包含关键词
时间: 2024-05-01 20:20:47 浏览: 8
Java中可以通过正则表达式来验证字符串中是否包含关键词。以下是一个示例代码:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class KeywordValidator {
public static void main(String[] args) {
String input = "This is a test string containing the keyword hello.";
String keyword = "hello";
boolean containsKeyword = containsKeyword(input, keyword);
System.out.println("The input string contains the keyword: " + containsKeyword);
}
public static boolean containsKeyword(String input, String keyword) {
Pattern pattern = Pattern.compile("\\b" + keyword + "\\b");
Matcher matcher = pattern.matcher(input);
return matcher.find();
}
}
```
在上面的示例代码中,`containsKeyword` 方法接受两个参数:一个输入字符串和一个关键词。该方法使用正则表达式来查找输入字符串中是否包含该关键词。如果找到该关键词,则返回 `true`,否则返回 `false`。需要注意的是,该方法使用了单词边界(`\b`)来确保只匹配关键词,而不是关键词的一部分。