Regex not working for the first time

I have a string, for example. 02112016. I want to make datetime from this line.

I tried:

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

But there's a problem. He returns "--".

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

But why does the first job s.sub(/(\d{2})(\d{2})(\d{4})/, "#{$1}-#{$2}-#{$3}")work?

+4
source share
3 answers

This is a really simple change here. $1, and friends are appointed only after the match is successful, and not during the match itself. If you want to use immediate values, do the following:

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

# => "02-11-2016"

\1 , $1. , gsub, $1 , \1 .

+4

.

r = /
    \d{2}     # match two digits
    (?=\d{4}) # match four digits in a positive lookahead
    /x        # free-spacing regex definition mode

r = /\d{2}(?=\d{4})/

String # gsub:

s.gsub(r) { |s| "#{s}-" }

:

"02112016".gsub(r) { |s| "#{s}-" }
  #=> "02-11-2016"
+3

, $1, $2 $3

.

,

s = "02112016"

p $1 #=> nil
p $2 #=> nil
p $3 #=> nil

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

p $1 #=> "02"
p $2 #=> "11"
p $3 #=> "2016"

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

.

, [], .

s = "#{s[0..1]}-#{s[2..3]}-#{s[4..-1]}"

"02-11-2016"
+2

Source: https://habr.com/ru/post/1659670/


All Articles