Skip to content

Instantly share code, notes, and snippets.

@ramonrails
Last active February 7, 2024 18:31
Show Gist options
  • Save ramonrails/28b929ad5570072412a8c53230c78656 to your computer and use it in GitHub Desktop.
Save ramonrails/28b929ad5570072412a8c53230c78656 to your computer and use it in GitHub Desktop.
reformat string with regex
# 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