Donato Donato - 1 year ago 198
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
Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download