jjjfff jjjfff - 1 year ago 70
Ruby Question

Regex doesn't work on the first time

I have a string e.g. 02112016. I want to make a datetime from this string.

I have tried:

s = "02112016"
s.sub(/(\d{2})(\d{2})(\d{4})/, "#{$1}-#{$2}-#{$3}")

But there is a problem. It returns

If I try this
s.sub(/(\d{2})(\d{2})(\d{4})/, "#{$1}-#{$2}-#{$3}")
again, it works:
. Now I can use to_datetime method.

But why doesn't the
s.sub(/(\d{2})(\d{2})(\d{4})/, "#{$1}-#{$2}-#{$3}")
work on the first time?

Answer Source

It's really a simple change here. $1 and friends are only assigned after the match succeeds, not during the match itself. If you want to use immediate values, do this:

s = "02112016"
s.sub(/(\d{2})(\d{2})(\d{4})/, '\1-\2-\3')

# => "02-11-2016"

Here \1 corresponds to what will be assigned to $1. This is especially important if you're using gsub since $1 tends to be the last match only while \1 is evaluated for each match individually.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download