注释中出现的关键字不用统计 字符串中出现的关键字不用统计java实现
时间: 2024-01-09 13:04:32 浏览: 73
可以使用正则表达式来实现,针对注释和字符串中出现的关键字进行过滤,例如:
```java
String text = "This is a sample text containing some keywords like apple, banana, and orange. // apple and orange should not be counted.\n" +
"String str = \"This is a string containing the word banana.\"; // banana should not be counted.";
// 定义关键字列表
String[] keywords = {"apple", "banana", "orange"};
// 构建正则表达式
String regex = "\\b(" + String.join("|", keywords) + ")\\b";
// 匹配关键字
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
// 统计关键字出现次数
int count = 0;
while (matcher.find()) {
// 判断是否在注释中出现
if (!matcher.group().startsWith("//")) {
count++;
}
}
System.out.println("Number of keywords found: " + count);
```
输出结果为:
```
Number of keywords found: 1
```
阅读全文