我的客户希望以这种方式屏蔽邮件中的电子邮件:
原始邮箱:
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);
并且工作正常:
但......不适用于第二种情况......
那么,在“@”之后适用于两种情况的正则表达式是什么?
请参阅我的答案底部的编辑,了解在.net中完成此操作的第二种方法(更短)。
(?:(?:^|(?<=@))([^.@])|\G(?!\A))[^.@](?:([^.@])(?=[.@]))?
替换:$1*$2
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));
}
}
[email protected]
[email protected]
u*****e@d****n.com
u*****o@d****n.com.co
(?:(?:^|(?<=@))([^.@])|\G(?!\A))
匹配以下任一项
(?:^|(?<=@))([^.@])
符合以下条件
(?:^|(?<=@))
匹配以下任一项
^
在线的开头断言位置
(?<=@)
正面看后方确保前面的符号字符@
字面意思
([^.@])
捕获列表中不存在的任何字符(除了点.
或字母@
符号之外的任何字符)到捕获组1
\G(?!\A)
在上一场比赛结束时断言位置[^.@]
匹配列表中不存在的任何字符(除了点.
或符号@
字符之外的任何字符)(?:([^.@])(?=[.@]))?
匹配以下零或一次
([^.@])
捕获列表中不存在的任何字符(除了点.
或符号@
字符之外的任何字符)到捕获组2
(?=[.@])
积极向前看确保以下是点.
或符号@
字符字面意思这种模式获得的结果与我原来的答案相同(除非给出长度为2的字符串:i.e. [email protected]
保持不变,而原始答案将使这个u*@domain.com
)。
C#(。net)支持可变长度的lookbehinds。感谢@Gurman的评论。他在正确的轨道上,可能不知道.net支持可变长度的lookbehinds。
(?<=(?:^|@)[^.]*)\B.\B
(?<=(?:^|@)[^.]*)
确保跟随匹配的正面观察
(?:^|@)
匹配行断言的开头或符号@
的文字
[^.]*
匹配任何字符,除了点字符.
字面上\B
匹配单词边界不匹配的位置.
匹配任何角色\B
匹配单词边界不匹配的位置