Replace all characters before @

Viewed 507

I have a string 'test@gmail.com'

I want to use regex for replace all characters before @ to star(*)

So expected result: '****@gmail.com'

I tried to use a regexp like this: 'test@gmail.com'.gsub(/^.*?(?=@)/, '*') but the result is *@gmail.com

or regexp like this: 'test@gmail.com'.gsub(/^[^@]*/, '*') but result is the same *@gmail.com

I don't want to use the .split method

May you give some advice please?

3 Answers

You can use

'test@gmail.com'.gsub(/.(?=.*@)/, '*')

See the regex demo and the Ruby demo.

The .(?=.*@) regex matches any one char other than line break chars that is immediately preceded with any zero or more chars other than line break chars and then a @ char.

It is unlikely there can be line break chars in the email addres, but if you ever need to support line breaks, do not forget to add m flag:

/.(?=.*@)/m

For the pattern you can use your second approach with the negated character class

^[^\s@]+(?=@)

The pattern matches:

  • ^ Start of string
  • [^\s@]+ Match 1+ times any char except @ or a whitspace char
  • (?=@) Assert @ to the right

Regex demo | Ruby demo

Then you can replace with the number of chars that were matched.

'test@gmail.com'.gsub(/^[^\s@]+(?=@)/){|m| '*' * m.length }

Output

****@gmail.com

Another option using the \G anchor:

\G[^@](?=[^@]*@)

Regex demo | Ruby demo

The pattern matches:

  • \G Assert the position at the end of previous match, or at the start (in this case)
  • [^@] Match any char except @ (add \s to not match space or newline)
  • (?=[^@]*@) Assert an @ to the right

Ruby example

'test@gmail.com'.gsub(/\G[^@](?=[^@]*@)/, '*')

Output

****@gmail.com

try this email.replaceAll("(^[^@]{0}|(?!^)\G)[^@]", "$1*")

Related