Donato Donato - 5 months ago 108
Ruby Question

regular expression to mask all but the last 4 digits of a social security number

I have the following string

ssn = "166557649"

And I want to replace it as such:

ssn = "*****7649"

When I use curly braces and specify a limit, it unfortunately replaces all the digits with a single "*":

=> "*7649"

I am able to use square brackets to replace multiple digits but it ends up replacing all of them:

=> "*********"

I tried this as well:

=> "*7649"

To clarify, I want to replace all but the last 4 digits. In other words, even if social security number had 20 digits (even though this will never happen), then it should replace the first 16 digits with asterick and just leave the last 4 visible.

vks vks

Try this.This uses a positive lookahead to check for 5 digits.Replace by *.See demo.