Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all characters before @

Tags:

regex

ruby

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?

like image 767
ADV Avatar asked Apr 02 '26 15:04

ADV


1 Answers

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
like image 84
Wiktor Stribiżew Avatar answered Apr 04 '26 09:04

Wiktor Stribiżew