【问题标题】:Replace capture group of dynamic size替换动态大小的捕获组
【发布时间】:2019-06-30 15:35:37
【问题描述】:

我想用星号替换 URL 的正则表达式的第一部分。取决于正则表达式,例如:

案例 1

http://example.com/path1/path2?abcd => http://example.com/path1/**********

正则表达式 1:/^(https?:\/\/.+\/path1\/?)(.+)/但我希望将第 2 组中的每个字符单独替换为 *

或

案例 2

person@example.com => ******@example.com

正则表达式 2

/^(.+)(@.+)$/,同样我希望 first 捕获组中的所有字符单独替换为 *

我曾尝试使用捕获组,但之后,我只剩下*@example.com

let email = `person@example.com`;
let regex = /^(.+)(@.+)$/;
console.log(email.replace(regex, '*$2'));

let url = `http://example.com/path1/path2?abcd`;
let regex = /^(https?:\/\/.+\/path1\/?)(.+)/;
console.log(url.replace(regex, '$1*'));

【问题讨论】:

    标签: javascript node.js regex


    【解决方案1】:

    你可以使用

    let email = `person@example.com`;
    let regex = /[^@]/gy;
    console.log(email.replace(regex, '*'));
    
    // OR
    console.log(email.replace(/(.*)@/, function ($0,$1) { 
         return '*'.repeat($1.length) + "@";
    }));

    和

    let url = `http://example.com/path1/path2?abcd`;
    let regex = /^(https?:\/\/.+\/path1\/?)(.*)/gy;
    console.log(url.replace(regex, (_,$1,$2) => `${$1}${'*'.repeat($2.length)}` ));
    // OR
    console.log(url.replace(regex, function (_,$1,$2) { 
         return $1 + ('*'.repeat($2.length)); 
    }));

    在.replace(/[^@]/gy, '*') 的情况下,字符串开头的除@ 之外的每个字符都替换为*(因此,直到第一个@)。

    在.replace(/(.*)@/, function ($0,$1) { return '*'.repeat($1.length) + "@"; }) 的情况下,直到最后一个@ 的所有字符都被捕获到第1 组,然后匹配替换为与第1 组值的长度+@ 字符长度相同的星号(它应该被添加到替换模式中,因为它被用作消费正则表达式部分的一部分)。

    .replace(regex, (_,$1,$2) => `${$1}${'*'.repeat($2.length)}` ) 遵循与上述案例相同的逻辑:捕获需要替换的部分,将其传递给匿名回调方法并使用一些代码来操作其值。

    【讨论】:

      【解决方案2】:

      您可以使用粘性标志 y(但 Internet Explorer 不支持它):

      s = s.replace(/(^https?:\/\/.*?\/path1\/?|(?!^))./gy, '$1*')
      

      但最简单的(并且到处都支持)是使用函数作为替换参数。

      s = s.replace(/^(https?:\/\/.+\/path1\/?)(.*)/, function (_, m1, m2) {
          return m1 + '*'.repeat(m2.length);
      });
      

      对于第二种情况,您可以简单地检查当前位置之后是否有@:

      s = s.replace(/.(?=.*@)/g, '*');
      

      【讨论】:

        猜你喜欢
        • 2011-02-24
        • 1970-01-01
        • 2021-12-01
        • 2021-02-13
        • 1970-01-01
        • 2011-10-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多