Created
October 11, 2012 00:20
-
-
Save flakyfilibuster/3869366 to your computer and use it in GitHub Desktop.
Regular Expression
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# # 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
In javascript it will look like this:
P.S. I suppose that format_ssns() should be called before hide_all_ssns(), right?