Java 实现在文本中精确查找某个字符串,例如有个文本的内容为
用户一览
公司用户一览
学校用户一览
'用户一览'
用户一览总结
在此文本中查找出 "用户一览"出现的次数 ,结果应为2 而不是5。
package com.example.test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WholeWordSearch {
/**
* begin regex.
*/
public static final String VIEW_FIND_START_REGEX = "(?<!([^\\W_]|[^\\x00-\\xff]))";
/**
* end regex.
*/
public static final String VIEW_FIND_END_REGEX = "(?!([^\\W_]|[^\\x00-\\xff]))";
public static void main(String[] args) throws FileNotFoundException {
String str = "用户一览";
String filePath = "E://file/test.txt";
System.out.println(wholeWordCount(str, filePath));
}
private static int wholeWordCount(String str, String filePath) throws FileNotFoundException {
String strRegex = VIEW_FIND_START_REGEX + escapeExprSpecialWord(str) + VIEW_FIND_END_REGEX;
Pattern pattern = Pattern.compile(strRegex);
int count = 0;
try (Scanner scan = new Scanner(new File(filePath), "utf-8");) {
while (true) {
if (scan.hasNext()) {
String s = scan.nextLine();
Matcher match = pattern.matcher(s);
if ((!str.isEmpty() && match.find())) {
count++;
}
} else {
break;
}
}
}
return count;
}
/**
* Escape special word.
* @param keyword sourceString
* @return target String
*/
public static String escapeExprSpecialWord(String keyword) {
if (!keyword.isEmpty()) {
String[] fbsArr = {"\\", "/", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|", "%", "'", "#", "<", ">"};
for (String key : fbsArr) {
if (keyword.contains(key)) {
keyword = keyword.replace(key, "\\" + key);
}
}
}
return keyword;
}
}