Java 实现在文本中精确查找字符串

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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容