使用正则表达式屏蔽域电子邮件地址

问题描述 投票:3回答:1

我的客户希望以这种方式屏蔽邮件中的电子邮件:

原始邮箱:

1 user [email protected]

2 [email protected] --->可以是gov.co,.com.mx等等

蒙面电子邮件:

1 U*****哦@的****你.com

2 U*****哦@的****你.com.co

对于第一种情况,我有这个

string pattern = @"(?<=[\w]{1})[\w-\._\+%]*(?=[\w]{1}@)"; // ---> mask before "@"
string p2 = @"(?<=[\w]{1})[\w-\+%]*(?=[\w]{1}[.])"; // --- > mask after "@"
string result = Regex.Replace(mail, pattern, m => new string('*', m.Length));
string newresult = Regex.Replace(result, p2, m => new string('*', m.Length));
Console.WriteLine("Masked email: {0}", newresult);

并且工作正常:

MaskedEmail first case

但......不适用于第二种情况......

那么,在“@”之后适用于两种情况的正则表达式是什么?

c# regex email
1个回答
3
投票

Original Answer

请参阅我的答案底部的编辑,了解在.net中完成此操作的第二种方法(更短)。

See regex in use here

(?:(?:^|(?<=@))([^.@])|\G(?!\A))[^.@](?:([^.@])(?=[.@]))?

替换:$1*$2

Usage

See code in use here

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(?:(?:^|(?<=@))([^.@])|\G(?!\A))[^.@](?:([^.@])(?=[.@]))?";
        string substitution = @"$1*$2";
        string input = @"[email protected]
[email protected]";
        RegexOptions options = RegexOptions.Multiline;

        Regex regex = new Regex(pattern, options);
        Console.WriteLine(regex.Replace(input, substitution));
    }
}

结果

Input

[email protected]
[email protected]

Output

u*****e@d****n.com
u*****o@d****n.com.co

说明

  • (?:(?:^|(?<=@))([^.@])|\G(?!\A))匹配以下任一项 (?:^|(?<=@))([^.@])符合以下条件 (?:^|(?<=@))匹配以下任一项 ^在线的开头断言位置 (?<=@)正面看后方确保前面的符号字符@字面意思 ([^.@])捕获列表中不存在的任何字符(除了点.或字母@符号之外的任何字符)到捕获组1 \G(?!\A)在上一场比赛结束时断言位置
  • [^.@]匹配列表中不存在的任何字符(除了点.或符号@字符之外的任何字符)
  • (?:([^.@])(?=[.@]))?匹配以下零或一次 ([^.@])捕获列表中不存在的任何字符(除了点.或符号@字符之外的任何字符)到捕获组2 (?=[.@])积极向前看确保以下是点.或符号@字符字面意思


Edit

这种模式获得的结果与我原来的答案相同(除非给出长度为2的字符串:i.e. [email protected]保持不变,而原始答案将使这个u*@domain.com)。

C#(。net)支持可变长度的lookbehinds。感谢@Gurman的评论。他在正确的轨道上,可能不知道.net支持可变长度的lookbehinds。

See regex in use here

(?<=(?:^|@)[^.]*)\B.\B

说明

  • (?<=(?:^|@)[^.]*)确保跟随匹配的正面观察 (?:^|@)匹配行断言的开头或符号@的文字 [^.]*匹配任何字符,除了点字符.字面上
  • \B匹配单词边界不匹配的位置
  • .匹配任何角色
  • \B匹配单词边界不匹配的位置
© www.soinside.com 2019 - 2024. All rights reserved.