Regex for even index replacement with asterisk in email

Viewed 297

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.

3 Answers

You don't need regex for this, you can use LINQ to select the characters you want based on their index from the username:

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

Will return u*e*n*m*1

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

Will return *s*r*a*e*

(Assuming you're using C#)

You can use regex /(\w)(\w)(?=.*@)/g with substitution $1*

console.log('username1@example.com'.replace(/(\w)(\w)(?=.*@)/g,'$1*'))
console.log('username@example.com'.replace(/(\w)(\w)(?=.*@)/g,'$1*'))

Using C# you could make use of the \G anchor and a capturing group and use a negated character class to not match a whitespace char or @.

Use a lookahead to make sure that there is only a single @ char present.

\G([^\s@])[^\s@](?=[^\s@]*@[^\s@]+(?!\S))
  • \G Assert position at the end of previous match (At the start)
  • ([^\s@]) Capture in group 1 matching any char exept a whitespace char or @
  • [^\s@] Match not a whitespace char or @
  • (?= Positive lookahead, assert what is at the right is
    • [^\s@]*@ Matches 0+ times any char except a whitspace char or @, then match @
    • [^\s@]+ Match 1+ times any char except a whitespace char or @
    • (?!\S) Negative lookahead, assert what is directly on the right is a non whitespace char
  • ) Close positive lookahead

In the replacement use

$1*

Regex demo | C# demo

enter image description here

For example

string[] strings = { "File name without 3 digit end.jpg",
        "username1@example.com",
        "username@example.com",                
        "username1@example@example.com",
        "username1@",
        "test",
        };

String pattern = @"\G([^\s@])[^\s@](?=[^\s@]*@[^\s@]+(?!\S))";
Regex regex = new Regex(pattern);
string substitution = @"$1*";
foreach(string str in strings)
{
    Console.WriteLine(regex.Replace(str, substitution));
}

Output

u*e*n*m*1@example.com
u*e*n*m*@example.com
username1@example@example.com
username1@
test
Related