Skip to content

Instantly share code, notes, and snippets.

@flakyfilibuster
Created October 11, 2012 00:20
Show Gist options
  • Save flakyfilibuster/3869366 to your computer and use it in GitHub Desktop.
Save flakyfilibuster/3869366 to your computer and use it in GitHub Desktop.
Regular Expression
# # Determine whether a string contains a Social Security number.
def has_ssn?(string)
/\d{3}-\d{2}-\d{4}/.match(string)
end
# Return the Social Security number from a string.
def grab_ssn(string)
string[/\d{3}-\d{2}-\d{4}/]
end
# Return all of the Social Security numbers from a string.
def grab_all_ssns(string)
ssn_array = []
has_ssn?(string) ? string.split(",").each {|e| ssn_array << grab_ssn(e)} : ssn_array
ssn_array
end
# Obfuscate all of the Social Security numbers in a string. Example: XXX-XX-4430.
def hide_all_ssns(string)
has_ssn?(string) ? grab_all_ssns(string).join(", ").gsub(/\d{3}-\d{2}/, 'XXX-XX') : string
end
# Ensure all of the Social Security numbers use dashes for delimiters.
# Example: 480.01.4430 and 480014430 would both be 480-01-4430.
def format_ssns(string)
digits = remove_special_chars(string)
is_9digits?(digits) ? beautiful_ssn(digits) : string
end
def remove_special_chars(string)
string.gsub(/[^\w\s]/, "")
end
def is_9digits?(input)
/\d{9}/.match(input) ? (return true) : (return false)
end
def beautiful_ssn(crappy_ssn)
crappy_ssn.gsub(/\d{5}/) {|s| s[0..2]+'-'+s[3..4]+'-'}.split(" ").join(", ")
end
@z0r1k
Copy link

z0r1k commented Oct 12, 2012

Hey,

I don't think that you need to use that complicated algorithm to fetch all SSNs in grab_all_ssns().
Apparently Ruby are not supporting global pattern matching via /g :(

So I suppose you can do something like this:

# Return all of the Social Security numbers from a string.
def grab_all_ssns(string)
    string.scan(/\d{3}-\d{2}-\d{4}/)
end

In javascript it will look like this:

// Return all of the Social Security numbers from a string.
function grab_all_ssns(string) {
    return string.match(/\d{3}-\d{2}-\d{4}/g) || [];
}

P.S. I suppose that format_ssns() should be called before hide_all_ssns(), right?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment