Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex doesn't work on the first time

Tags:

regex

ruby

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: "02-11-2016". 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?

like image 792
jjjfff Avatar asked Jan 06 '23 03:01

jjjfff


1 Answers

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.

like image 106
tadman Avatar answered Jan 11 '23 23:01

tadman