替换动态大小的捕获组 [英] Replace capture group of dynamic size

查看:29
本文介绍了替换动态大小的捕获组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to replace the first part of regex for a URL with asterisks. Depending on the regex, for example:

案例 1

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

Regex 1:/^(https?:\/\/.+\/path1\/?)(.+)/但我想要每个字符组 2 单独替换为 *

Regex 1: /^(https?:\/\/.+\/path1\/?)(.+)/but I want each character in group 2 to be replaced individually with *

案例 2

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

正则表达式 2

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

/^(.+)(@.+)$/, similarly I want all characters in the first capture group to be replaced individually with *

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

I have tried to use capture groups, but then, I'm left with *@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*'));

推荐答案

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

You can use the sticky flag y (but Internet Explorer doesn't support it):

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

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

But the simplest (and that is supported everywhere), is to use a function as replacement parameter.

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

<小时>

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

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

这篇关于替换动态大小的捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆