简体   繁体   English

此正则表达式模式的C#等效项

[英]C# equivalent for this regex pattern

I have this regular expression pattern: .{2}\\@.{2}\\K|\\..*(*SKIP)(?!)|.(?=.*\\.) 我有这个正则表达式模式: .{2}\\@.{2}\\K|\\..*(*SKIP)(?!)|.(?=.*\\.)

It works perfectly to convert to replace the matches to get 它非常适合转换以替换匹配以获取

trabc@abtrec.com.lo => ***bc@ab*****.com.lo

demomail@demodomain.com => ******il@de*********.com

But when I try to use it on C# the \\K and the (*SKIP) and (*F) are not allowed. 但是,当我尝试在C#上使用它时,不允许使用\\ K以及(* SKIP)和(* F)。

what will be the c# version of this pattern? 此模式的C#版本将是什么? or do you know a simpler way to mask the email without the unsupported pattern entries? 还是您知道一种在没有不受支持的模式条目的情况下掩盖电子邮件的更简单方法?

Demo 演示

UPDATE: 更新:

(*SKIP): this verb causes the match to fail at the current starting position in the subject if the rest of the pattern does not match (* SKIP):如果其余模式不匹配,则该动词会使匹配在主题的当前起始位置失败

(*F): Forces a matching failure at the given position in the pattern (the same as (?!) (* F):在模式中的给定位置强制匹配失败(与(?!相同)

Try this regex: 试试这个正则表达式:

\w(?=.{2,}@)|(?<=@[^\.]{2,})\w

Click for Demo 点击演示

Explanation: 说明:

  • \\w - matches a word character \\w匹配单词字符
  • (?=.{2,}@) - positive lookahead to find the position immediately followed by 2+ occurrences of any character followed by @ (?=.{2,}@) -正向查找以立即找到位置,然后再出现2个以上的任意字符,再跟@
  • | - OR - 要么
  • (?<=@[^\\.]{2,}) - positive lookbehind to find the position immediately preceded by @ followed by 2+ occurrences of any character that is not a . (?<=@[^\\.]{2,}) -向后查找,以查找紧接@的位置,然后出现2​​个以上非字符的位置.
  • \\w - matches a word character. \\w匹配单词字符。

Replace each match with a * 将每个匹配项替换为*

You can achieve the same result with a regex that matches items in one block, and applying a custom match evaluator: 您可以使用正则表达式来实现相同的结果,该正则表达式匹配一个块中的项目,并应用自定义匹配评估器:

var res = Regex.Replace(
    s
,   @"^.*(?=.{2}\@.{2})|(?<=.{2}\@.{2}).*(?=.com.*$)"
,   match => new string('*', match.ToString().Length)
);

The regex has two parts: 正则表达式包含两个部分:

  • The one on the left ^.*(?=.{2}\\@.{2}) matches the user name portion except the last two characters 左边的^.*(?=.{2}\\@.{2})匹配用户名部分,但最后两个字符除外
  • The one on the right (?<=.{2}\\@.{2}).*(?=.com.*$) matches the suffix of the domain up to the ".com..." ending. 右边的那个(?<=.{2}\\@.{2}).*(?=.com.*$)匹配域的后缀,直到“ .com ...”结尾。

Demo. 演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM