Last active
February 7, 2024 18:31
-
-
Save ramonrails/28b929ad5570072412a8c53230c78656 to your computer and use it in GitHub Desktop.
reformat string with regex
This file contains 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
# Usage: | |
# tested with 8, 9, 10, 11, 12 digit phone numbers | |
# | |
# ar = ["(+1) 888 33x19", "95606 3354", "555 123 1234", "0 95606 33544", "(+91) 95606 33544"] | |
# ar.map {|e| format_string(e) } | |
# => ["188-833-19", "956-063-354", "555-123-12-34", "095-606-335-44", "919-560-633-544"] | |
# | |
def format_string(s) | |
# step #1 => remove all non-digits | |
# step #2(a) => pick the digits in groups of 333[2][2] | |
# step #2(b) => place the groups as 3-3-3-2-2 | |
# step #3 => replace any consecutive '-'(es) with a single '-' | |
# | |
s.gsub(/[^0-9]/,'').gsub(/(...)(...)(...)?(..)?(..)/,'\1-\2-\3-\4-\5').gsub(/\-+/, '-') | |
end | |
# Note: I solved this as a challenge somewhere. Seemed interesting enough to share with fellow rubyists. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment