注释中出现的关键字不用统计 字符串中出现的关键字不用统计java实现
时间: 2024-01-09 14:04:32 浏览: 39
可以使用正则表达式来实现,针对注释和字符串中出现的关键字进行过滤,例如:
```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
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)