正则的exec神器!

正则的模式匹配法exec,必须了解,帮助你精准地去修改/拼接字符串,并且可以大大帮助你减少出错的概率。

一个需求,效果如下,即先在大输入框里写文案,然后在下面的小输入框里写上你要匹配的文案,把匹配到的文案标红。

我的影片.gif

这里的关键就在于,如何匹配到,并且成功拼接。

此处省略100字,上关键代码:(FYI,在vue框架中处理的)

    data () {
        return {
            processIdx: 0, // 记录一开始的位置
            reg: "", // 输入的正则
            r: "", // 最后显示带颜色的字符串
            res: [], // 每次匹配的结果
            sample: "", // 存放与原始文本相同的文本,避免改变原始字符串
        }
    }

  methods: {
        initProcess() { // 每次点击验证,都需要重置
            this.processIdx = 0;
            this.reg = "";
            this.r = "";
            this.res = [];
            this.sample = "";
        },
        processText() { 
            // 「关键方法」「关键方法」「关键方法」:处理文本颜色,
            //  就是利用正则的exec方法,每次都会改变index和lastIndex值。
            this.res = this.reg.exec(this.form.sample);
            if (!this.res) {
                this.r += this.sample.slice(this.processIdx);
                this.vHtml4Model = this.r;
            } else {
                this.r += this.sample.slice(this.processIdx, this.res.index);
                let p = this.sample.slice(this.res.index, this.reg.lastIndex);
                p = `<span style="color:red">${p}</span>`;
                this.r += p;
                this.processIdx = this.reg.lastIndex;
                this.processText(); // 递归调用
            }
        },
        matchReg() { // 点击“验证”按钮的时候调用的方法
            this.initProcess();
            if (!this.form.sample) return this.$message("请输入日志样例");
            if (this.regExpression) {
                this.showSampleInput = false; // 无关代码,可忽略
                this.showSampleText = true; // 无关代码,可忽略
                this.reg = new RegExp(this.regExpression, "g");
                this.sample = this.form.sample.toString();
                this.processText();
            } else {
                this.$message("请输入正则表达式");
            }
        },
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值