Regex - replacing part of a matched group possible?

Viewed 200

Is it possible to replace half or x characters of a matched group?

I have had a request for a partial email capturing, so something like example123@abcdef.com becomes ***mple123@***def.com

I can do this if the characters before and after the @ are 3 characters long,

([^|@]{0,3})([^]{0,3})

This captures 123@abc.com perfectly and I can substitute for ***@***.com but if it's over 3 characters long on each end, for instance example123@abcdef.com it becomes ******e123@abcdef.com

The other way I can see is capture everything until the @ and everything to the . but then this won't be a partial capture. Is this possible?

1 Answers

You can use

sed -E 's/^[^@]{0,3}|(@)[^.]{0,3}/\1***/g'

Details

  • -E - enables the POSIX ERE syntax that does not require too much escaping here
  • ^[^@]{0,3} - zero to three occurrences of any char other than a @ at the start of the string
  • | - or
  • (@) - Group 1: a @ char
  • [^.]{0,3} - zero to three occurrences of any char other than a .
  • \1*** replaces with Group 1 value + ***.
Related