3 Replies - 225 Views - Last Post: 27 December 2013 - 12:48 PM Rate Topic: -----

#1 heaphyg  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 85
  • Joined: 30-August 13

regex logic question

Posted 27 December 2013 - 10:17 AM

I understand everything except how the '\1-\2-\3-'. I understand that that section of the code manages to assign dashes in the appropriate location of the inputed string but i'm not sure exactly how.
I don't understand the 1 the 2 and the 3 in the substitution regex. Thank you for your time.

# Example: 480.01.4430 and 480014430 would both be 480-01-4430.
def format_ssns(string)
  string.gsub /\b(\d{3})\D?(\d{2})\D?(\d{4})\b/, '\1-\2-\3'


This post has been edited by Atli: 27 December 2013 - 10:26 AM
Reason for edit:: Fixed the [code] tags.


Is This A Good Question/Topic? 0
  • +

Replies To: regex logic question

#2 andrewsw  Icon User is offline

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3251
  • View blog
  • Posts: 10,902
  • Joined: 12-December 12

Re: regex logic question

Posted 27 December 2013 - 10:57 AM

\1 refers to the first capture group, which is the values caught between the first pair of round brackets, (\d{3}). The 3 numbers caught here are re-inserted in place of \1. \2 refers to the second capture group.

So the output will be: 123-45-6789
Was This Post Helpful? 3
  • +
  • -

#3 heaphyg  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 85
  • Joined: 30-August 13

Re: regex logic question

Posted 27 December 2013 - 11:28 AM

Thanks!
Was This Post Helpful? 0
  • +
  • -

#4 andrewsw  Icon User is offline

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3251
  • View blog
  • Posts: 10,902
  • Joined: 12-December 12

Re: regex logic question

Posted 27 December 2013 - 12:48 PM

You are welcome.

Rubular should be your pal.

This post has been edited by andrewsw: 27 December 2013 - 12:50 PM

Was This Post Helpful? 2
  • +
  • -

Page 1 of 1