首页 > 解决方案 > Regex for even index replacement with asterisk in email

问题描述

I want to replace letter of even indexes with asterisk (*) in my email username before @ sign using Regular expression.

I made regex but it is once work with even or work with odd length of username in email.

I want a single regex to handle both the expression First letter must visible all the time in given email.

Please help using regex.

Example: username@example.com

    Regex: Works with odd length username input Expression: (?!^).(?=([^.]([a-zA-Z0-9]{2})*)@) 
    Input : username1@example.com
    Output: u*e*n*m*1@example.com

    Regex: Works with Even length username input Expression: (?!^).(?=(([a-zA-Z0-9]{2})*)@) 
    Input : username@example.com
    Output: u*e*n*m*@example.com

But I want a single expression for both kind of username length email.

Thanks in advance.

标签: javascriptc#regex

解决方案


您不需要正则表达式,您可以使用 LINQ 根据用户名中的索引选择所需的字符:

var username = "username1@example.com".Split('@')[0];
var asterisked = string.Concat(username.Select((x,i) => i % 2 == 1 ? '*' : x));

将返回u*e*n*m*1

var username = "username1@example.com".Split('@')[0];
var asterisked = string.Concat(username.Select((x,i) => i % 2 == 0 ? '*' : x));

将返回*s*r*a*e*

(假设您使用的是 C#)


推荐阅读