I have a string '[email protected]'
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:
'[email protected]'.gsub(/^.*?(?=@)/, '*') but the result is *@gmail.com
or regexp like this:
'[email protected]'.gsub(/^[^@]*/, '*') but result is the same *@gmail.com
I don't want to use the .split method
May you give some advice please?
You can use
'[email protected]'.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With