0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
会员中心
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

字符串替换研究

京东云 来源:jf_75140285 作者:jf_75140285 2025-04-02 14:58 次阅读
加入交流群
微信小助手二维码

扫码添加小助手

加入工程师交流群

一、背景

需求非常简单,给定一组关键词,需要将商品名称中出现过的关键字替换掉;

如:skuName="HUAWEI Pura 70 Pro 国家补贴500元 羽砂黑 12GB+512GB 超高速风驰闪拍 华为鸿蒙智能手机" 需要替换成

skuName="HUAWEI Pura 70 Pro 羽砂黑 12GB+512GB 超高速风驰闪拍 华为鸿蒙智能手机" 这里的关键字"国家补贴500元";

直接skuName.replace("国家补贴500元", ""),不就可以了吗?如果是一组,那就循环替换就完了嘛,再考虑到关键字前缀问题,对这一组关键词,按字符长度进行排序,先替换长的关键词,再替换短的就ok了;

如果这一组关键词非常多,上千个怎么办?真实场景也是这样的,一般需要替换的关键词都是比较多,并且使用String.replace上线后,直接CPU打满,基本不可用;

这个字段替换本质上与敏感词过滤是一样的原理,针对敏感词的深入研究,出现了 Aho-Corasick(AC自动机) 算法

Aho-Corasick(AC自动机)是一种多模式字符串匹配算法,结合了Trie树的前缀匹配能力和KMP算法的失败跳转思想,能够在单次文本扫描中高效匹配多个模式串。其核心优势在于时间复杂度为O(n + m + z)(n为文本长度,m为模式串总长度,z为匹配次数),适用于敏感词过滤、基因序列分析等场景。



二、方案

针对这几种算法进行对比;

字符串替换,定义一个接口,通过4个不同的方案实现,进行性能对比

public interface Replacer {
    String replaceKeywords(String text);
}

2.1 String.replace 方案

这种方案最简单,也是关键词少的时候,最有效,最好用的;

public class StrReplacer implements Replacer {
    private final List< String > keyWordList;
    public StrReplacer(String keyWords) {
        this.keyWordList = Lists.newArrayList(keyWords.split(";"));
        // 按关键字长度降序排序,确保长关键字优先匹配
        keyWordList.sort((a, b) -> Integer.compare(b.length(), a.length()));
    }
    /**
    * 替换文本中所有匹配的关键字为空字符串
    */
    @Override
    public String replaceKeywords(String text) {
        String newTxt = text;
        for (String s : keyWordList) {
            newTxt = newTxt.replace(s, "");
        }
        return newTxt;
    }
}

2.2 使用正则替换

String.replace本质,还是使用正则进行替换的,通过代码实现使用编译好的正则进行替换性能会好于直接使用replace;

String.replace的实现

public String replace(CharSequence target, CharSequence replacement) {
    return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
            this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}

使用正则替换的实现

public class PatternReplacer implements Replacer {
    // 预编译正则表达式模式
    private final Pattern pattern;
    public PatternReplacer(String keyWords) {
        List< String > keywords = Lists.newArrayList(keyWords.split(";"));
        // 按关键字长度降序排序,确保长关键字优先匹配
        keywords.sort((a, b) -> Integer.compare(b.length(), a.length()));
        // 转义每个关键字并用|连接
        String regex = keywords.stream()
                .map(Pattern::quote)
                .collect(Collectors.joining("|"));

        this.pattern = Pattern.compile(regex);
    }

    // 替换方法
    @Override
    public String replaceKeywords(String skuName) {
        return pattern.matcher(skuName).replaceAll("");
    }
}

2.3 使用Aho-Corasick(AC自动机) 算法实现

java中已有现成的算法实现,源代码github-robert-bor/aho-corasick,

引入jar包

< dependency >
    < groupId >org.ahocorasick< /groupId >
    < artifactId >ahocorasick< /artifactId >
    < version >0.6.3< /version >
< /dependency >

基于 Aho-Corasick 算法的字符串替换实现

public class AhoCorasickReplacer implements Replacer {
    private final Trie trie;
    public AhoCorasickReplacer(String keyWords) {
        // 构建Aho-Corasick自动机
        Trie.TrieBuilder builder = Trie.builder().ignoreOverlaps().onlyWholeWords();
        //trie.caseInsensitive();
        //trie.onlyWholeWords();
        for (String s : keyWords.split(";")) {
            builder.addKeyword(s);
        }
        this.trie = builder.build();
    }
    /**
     * 替换文本中所有匹配的关键字为空字符串
     */
    @Override
    public String replaceKeywords(String text) {
        if (text == null || text.isEmpty()) {
            return text;
        }
        StringBuilder result = new StringBuilder();
        Collection< Emit > emits = trie.parseText(text); // 获取所有匹配结果
        int lastEnd = 0;
        for (Emit emit : emits) {
            int start = emit.getStart();
            int end = emit.getEnd();

            // 添加未匹配的前缀部分
            if (start > lastEnd) {
                result.append(text, lastEnd, start);
            }
            // 跳过匹配的关键字(即替换为空)
            lastEnd = end + 1; // 注意:end是闭区间,需+1移动到下一个字符
        }
        // 添加剩余未匹配的后缀部分
        if (lastEnd <= text.length() - 1) {
            result.append(text.substring(lastEnd));
        }
        return result.toString();
    }
}

2.4 自己实现Trie树算法实现

通过deepseek等人工智能,是非常容易自己实现一个Trie树,我们就只实现字符串替换的功能,其他的就不使用了;

Trie树,又叫字典树,前缀树(Prefix Tree),单词查找树,是一种多叉树的结构.

wKgZO2fs3_-AbLcgAAFcXyyz9_Y318.png

结构说明: 表示根节点(空节点)

每个节点表示一个字符

粉色节点表示单词结束标记(使用 CSS class 实现)

路径示例:

root → c → a → t 组成 "cat"

root → c → a → r 组成 "car"

root → d → o → g 组成 "dog"

public class TrieKeywordReplacer implements Replacer {

    private final Trie trie;

    @Override
    public String replaceKeywords(String text) {
        return trie.replaceKeywords(text, "");
    }

    public TrieKeywordReplacer(String keyWords) {
        Trie trie = new Trie();
        for (String s : keyWords.split(";")) {
            trie.insert(s);
        }
        this.trie = trie;
    }

    static class TrieNode {
        Map< Character,TrieNode > children;
        boolean isEndOfWord;

        public TrieNode() {
            children = new HashMap<  >();
            isEndOfWord = false;
        }
    }

    static class Trie {
        private TrieNode root;

        public Trie() {
            root = new TrieNode();
        }

        private synchronized void insert(String word) {
            TrieNode node = root;
            for (char c : word.toCharArray()) {
                if (node.children.get(c) == null) {
                    node.children.put(c, new TrieNode());
                }
                node = node.children.get(c);
            }
            node.isEndOfWord = true;
        }

        public String replaceKeywords(String text, String replacement) {
            StringBuilder result = new StringBuilder();
            int i = 0;
            while (i < text.length()) {
                TrieNode node = root;
                int j = i;
                TrieNode endNode = null;
                int endIndex = -1;
                while (j < text.length() && node.children.get(text.charAt(j)) != null) {
                    node = node.children.get(text.charAt(j));
                    if (node.isEndOfWord) {
                        endNode = node;
                        endIndex = j;
                    }
                    j++;
                }
                if (endNode != null) {
                    result.append(replacement);
                    i = endIndex + 1;
                } else {
                    result.append(text.charAt(i));
                    i++;
                }
            }
            return result.toString();
        }
    }
}

4个实现类对象的大小对比

对象大小
StrReplacer 12560
PatternReplacer 21592
TrieKeywordReplacer 184944
AhoCorasickReplacer 253896

性能对比

说明:待替换一组关键词共 400个;JDK1.8

StrReplacer PatternReplacer TrieKeywordReplacer AhoCorasickReplacer
单线程循环1w次,平均单次性能(ns) 21843ns 28846ns 532ns 727ns
名称中只有1个待替换的关键词,2个并发线程,循环1w次,平均单次性能(ns),机器 CPU 30%左右 23444ns 39984ns 680ns 1157ns
名称中只有20待替换的关键词,2个并发线程,循环1w次,平均单次性能(ns),机器 CPU 30%左右 252738ns 114740ns 33900ns 113764ns
名称中只有无待替换的关键词,2个并发线程,循环1w次,平均单次性能(ns),机器 CPU 30%左右 22248ns 9253ns 397ns 738ns



通过性能对比,自己实现的Trie树的性能是最好的,因为只做了替换的逻辑,没有实现其他功能,其次是使用AhoCorasick算法,因为使用 AhoCorasick算法,实现字符串替换是最基本的功能,AhoCorasick算法,还能精准的匹配到在什么地方,出现过多少次等信息,功能非常强大;

通过对比编译好的正则性能确实是比使用原生String.replace;

public class ReplacerTest {

    @Test
    public void testTrieKeywordReplacer(){
        //String name = skuName;
        //String expected = v2;
        //String name = "三星Samsung Galaxy S25+ 超拟人AI助理 骁龙8至尊版 AI拍照 翻译手机 游戏手机 12GB+256GB 冷川蓝";
        //String expected = name;

        String name = keyWords;
        String expected = v1;
        int cnt = 2;
        Replacer replacer = new TrieKeywordReplacer(keyWords);
        check(replacer, name, expected);
        for (int i = 0; i < cnt; i++) {
            checkExec(replacer, name);
        }
    }

    @Test
    public void 替换所有关键字() throws InterruptedException {
        //String name = skuName;
        //String expected = v2;
        //String name = "三星Samsung Galaxy S25+ 超拟人AI助理 骁龙8至尊版 AI拍照 翻译手机 游戏手机 12GB+256GB 冷川蓝";
        //String expected = name;

        String name = keyWords;
        String expected = v1;

        int cnt = 2;
        System.out.println("替换:" + name);
        Replacer replacer = new StrReplacer(keyWords);
        check(replacer, name, expected);
        for (int i = 0; i < cnt; i++) {
            checkExec(replacer, name);
        }


        replacer = new PatternReplacer(keyWords);
        check(replacer, name, expected);
        for (int i = 0; i < cnt; i++) {
            checkExec(replacer, name);
        }

        replacer = new TrieKeywordReplacer(keyWords);
        check(replacer, name, expected);
        for (int i = 0; i < cnt; i++) {
            checkExec(replacer, name);
        }

        replacer = new AhoCorasickReplacer(keyWords);
        check(replacer, name, expected);
        for (int i = 0; i < cnt; i++) {
            checkExec(replacer, name);
        }



    }


    @Test
    public void 无关键字替换() throws InterruptedException {
        //String name = skuName;
        //String expected = v2;
        String name = "三星Samsung Galaxy S25+ 超拟人AI助理 骁龙8至尊版 AI拍照 翻译手机 游戏手机 12GB+256GB 冷川蓝";
        String expected = name;

        //String name = keyWords;
        //String expected = v1;

        int cnt = 1;
        System.out.println("替换:" + name);
        Replacer replacer = new StrReplacer(keyWords);
        check(replacer, name, expected);
        for (int i = 0; i < cnt; i++) {
            checkExec(replacer, name);
        }


        replacer = new PatternReplacer(keyWords);
        check(replacer, name, expected);
        for (int i = 0; i < cnt; i++) {
            checkExec(replacer, name);
        }

        replacer = new TrieKeywordReplacer(keyWords);
        check(replacer, name, expected);
        for (int i = 0; i < cnt; i++) {
            checkExec(replacer, name);
        }

        replacer = new AhoCorasickReplacer(keyWords);
        check(replacer, name, expected);
        for (int i = 0; i < cnt; i++) {
            checkExec(replacer, name);
        }



    }

    @Test
    public void 有1个关键字替换() throws InterruptedException {
        //String name = skuName;
        //String expected = v2;
        //String name = "三星Samsung Galaxy S25+ 超拟人AI助理 骁龙8至尊版 AI拍照 翻译手机 游戏手机 12GB+256GB 冷川蓝";
        //String expected = name;

        //String name = keyWords;
        //String expected = v1;

        String name = "HUAWEI Pura 70 Pro 国家补贴500元 羽砂黑 12GB+512GB 超高速风驰闪拍 华为鸿蒙智能手机";
        String expected = "HUAWEI Pura 70 Pro 500元 羽砂黑 12GB+512GB 超高速风驰闪拍 华为鸿蒙智能手机";

        int cnt = 1;
        System.out.println("替换:" + name);
        Replacer replacer = new StrReplacer(keyWords);
        check(replacer, name, expected);
        for (int i = 0; i < cnt; i++) {
            checkExec(replacer, name);
        }


        replacer = new PatternReplacer(keyWords);
        check(replacer, name, expected);
        for (int i = 0; i < cnt; i++) {
            checkExec(replacer, name);
        }

        replacer = new TrieKeywordReplacer(keyWords);
        check(replacer, name, expected);
        for (int i = 0; i < cnt; i++) {
            checkExec(replacer, name);
        }

        replacer = new AhoCorasickReplacer(keyWords);
        check(replacer, name, expected);
        for (int i = 0; i < cnt; i++) {
            checkExec(replacer, name);
        }



    }


    static void check(Replacer replacer, String name, String expected) {
        System.out.println(replacer.getClass().getName()+",对象大小:"+ObjectSizeCalculator.getObjectSize(replacer));
        String newTxt = replacer.replaceKeywords(name);
        //System.out.println(newTxt);
        Assert.assertEquals(replacer.getClass().getName() + ",对比不一致!", expected, newTxt);
    }


    void checkExec(Replacer replacer, String name) {
        String newTxt = replacer.replaceKeywords(name);
        int nThreads  = 2;
        ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
        CountDownLatch downLatch = new CountDownLatch(nThreads);
        int i = 0;
        while (i++ < nThreads) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    int i = 0;
                    long ns = System.nanoTime();
                    while (i++ < 100000) {
                        replacer.replaceKeywords(name);
                    }
                    String name = replacer.getClass().getName();
                    downLatch.countDown();
                    System.out.println(StringUtils.substring(name, name.length() - 50, name.length()) + "ti=" + i + ", t耗时:" + (System.nanoTime() - ns) / i + "ns");
                }
            });
        }
        executorService.shutdown();
        try {
            downLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

最后

1、使用现成的AhoCorasick算法进行实现,是性能与稳定性最优的选择,非常强调性能,还是可以自己实现Trie树来实现;

2、在真实的使用过程中,因为大部分的商品名称最多出现几个关键词,并且待替换的关键词往往都是比较多的,可以将这么关键词找出找出几个有代表性能的词,做前置判断,商品名称中是否存在;再进行全量替换;

如待替换的关键词有:政府补贴、国补、支持国补; 那么我们并不是直接就循环这个待替换的关键词组,而是找出这么关键词中都有的关键字”补”先判断商品名称中是否存在“补”字后,再做处理; 这里的前置判断,还可以使用布隆过滤器实现;


public String replaceKeywords (String skuName){
    Replacer replacer = new AhoCorasickReplacer(keyWords);
    if(skuName.contains("补")){
        return  replacer.replaceKeywords(skuName);
    } else {
        return skuName;
    }
}

参考

- [1] Aho-Corasick 算法 AC自动机实现

- [2] Trie字典树

审核编辑 黄宇

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 算法
    +关注

    关注

    23

    文章

    4763

    浏览量

    97279
  • 字符串
    +关注

    关注

    1

    文章

    594

    浏览量

    23077
收藏 人收藏
加入交流群
微信小助手二维码

扫码添加小助手

加入工程师交流群

    评论

    相关推荐
    热点推荐

    字符串关联数字变量如何使用?我们的地址都是16位数据,可以使用16位数字变量显示字符串吗?

    字符串关联数字变量如何使用?我们的地址都是16位数据,可以使用16位数字变量显示字符串吗?
    发表于 12-15 08:24

    飞凌嵌入式ElfBoard-标准IO接口之格式化输出

    。...:表示附加可变参数,根据不同的 format 字符串,函数可能需要一系列的附加参数,每个参数包含了一个要被插入的值,替换了 format 参数中指定的每个 % 标签。参数的个数应与 % 标签
    发表于 11-11 08:43

    如何使用 NuMaker 板和 Mbed OS 上的连接字符串连接到 Azure IoT?

    使用 NuMaker 板和 Mbed OS 上的连接字符串连接到 Azure IoT
    发表于 09-04 07:46

    LM3466 多 LED 电流平衡器技术手册

    到电源的数或每个 LED 的正向电压 字符串。 如果任何 LED 灯在运行过程中打开,LM3466 会自动平衡通过所有剩余活动 LED 灯的电源电流。 如 因此,即使一些 LED
    的头像 发表于 08-29 14:27 872次阅读
    LM3466 多<b class='flag-5'>串</b> LED 电流平衡器技术手册

    labview如何生成一个带字符串返回的dll

    labview如何生成一个dll,如下图,要求一个输入,类型是字符串,返回类型也是字符串
    发表于 08-28 23:20

    在Python中字符串逆序有几种方式,代码是什么

    对于一个给定的字符串,逆序输出,这个任务对于python来说是一种很简单的操作,毕竟强大的列表和字符串处理的一些列函数足以应付这些问题 了,今天总结了一下python中对于字符串的逆序输出的几种常用
    的头像 发表于 08-28 14:44 804次阅读

    harmony-utils之StrUtil,字符串工具类

    harmony-utils之StrUtil,字符串工具类 harmony-utils 简介与说明 [harmony-utils] 一款功能丰富且极易上手的HarmonyOS工具库,借助众多实用工具类
    的头像 发表于 07-03 11:32 402次阅读

    STM32C031C6使用的是UART2通讯,通过printf()函数发送字符串时,汉字错码怎么解决?

    使用的是UART2通讯,通过printf()函数发送字符串时,汉字错码(见下图),应该是KEIL哪里没有设置好的问题。 启用了UART2的中断接收,可以接收到串口调试助手的数据,但是缓存区的指针没有归零,下次接收时缓存区中的内容接续(如下图所示),不知道用什么命令来清除缓存区(即让指针归零)。
    发表于 03-07 12:30

    为什么无法使用“numpy.array”函数加载图像文件?

    替换为图像文件: random_input_data = np.array(r\"image.png\").astype(np.float16) 遇到错误: ValueError: 无法将字符串转换为浮点数
    发表于 03-06 07:31

    请问如何用Verilog实现将ascaii码数值字符串转换成定点数?

    我需要接收一个ascaii码字符串,内容是12位有效数字的数值,带小数。我不知道怎么把小数部分转换成定点数。
    发表于 01-23 21:57

    字符串在数据库中的存储方式

    数据库是现代信息技术中存储和管理数据的核心组件。字符串作为最常见的数据类型之一,在数据库中的存储方式对其性能和可扩展性有着重要影响。 数据类型 固定长度字符串 :如CHAR类型,它为每个字符串分配
    的头像 发表于 01-07 15:41 1278次阅读

    字符串在编程中的应用实例

    字符串在编程中有着广泛的应用,它们被用于表示文本数据、处理用户输入、构建动态内容等。以下是一些字符串在编程中的应用实例: 1. 用户输入与输出 用户输入 :程序通常需要从用户那里获取输入,这些输入通
    的头像 发表于 01-07 15:33 1156次阅读

    字符串字符数组的区别

    在编程语言中,字符串字符数组是两种基本的数据结构,它们都用于存储和处理文本数据。尽管它们在功能上有一定的重叠,但在内部表示、操作方式和使用场景上存在显著差异。 1. 内部表示 字符串 字符串
    的头像 发表于 01-07 15:29 1719次阅读

    字符串反转的实现方式

    在编程中,字符串反转是一个基础而重要的操作,它涉及到将一个字符串中的字符顺序颠倒过来。这个操作在多种编程语言中都有不同的实现方式,本文将探讨几种常见的字符串反转方法。 1. 递归方法
    的头像 发表于 01-07 15:27 1276次阅读

    字符串处理方法 字符串转数字的实现

    在编程中,将字符串转换为数字是一个常见的需求。不同的编程语言有不同的方法来实现这一功能。以下是一些常见编程语言中的字符串转数字的实现方法: Python 在Python中,可以使用内置的 int
    的头像 发表于 01-07 15:26 1428次阅读