tags:

views:

128

answers:

6

Hi I'm new to Ruby and regular expressions. I'm trying to use a regular expression to remove any zeros from the month or day in a date formatted like "02/02/1980" => "2/2/1980"

def m_d_y
  strftime('%m/%d/%Y').gsub(/0?(\d{1})\/0?(\d{1})\//, $1 + "/" + $2 + "/" )
end

What is wrong with this regular expression?

Thanks.

A: 

Try /(?<!\d)0(\d)/

"02/02/1980".gsub(/(?<!\d)0(\d)/,$1)
=> "2/2/1980"
S.Mark
why is this not working... It work even interpret properly
Alex Baranosky
Huh? On what Ruby interpreter did you do that? AFAIK (and according http://www.regular-expressions.info/lookaround.html) Ruby does not support look-behinds *and* replacement-interpolation is done through `'\1'` (including quotes!) instead of `$1`.
Bart Kiers
I am not sure with other ruby, but ruby 1.9 support that.
S.Mark
A: 

The problem is that it won't match valid dates so your replacement will mangle valid strings. To fix:

Regex: (^|(?<=/))0

Replacement: ''

Max Shawabkeh
Why is Ruby saying this is a syntax error?
Alex Baranosky
Ruby does not support look-behinds. See: http://www.regular-expressions.info/lookaround.html
Bart Kiers
+2  A: 

You can simply remove 0s in parts that ends with a slash.

Works for me

require "date"

class Date
    def m_d_y
      strftime('%m/%d/%Y').gsub(/0(\d)\//, "\\1/")
    end
end

puts Date.civil(1980, 1, 1).m_d_y
puts Date.civil(1980, 10, 1).m_d_y
puts Date.civil(1980, 1, 10).m_d_y
puts Date.civil(1908, 1, 1).m_d_y
puts Date.civil(1908, 10, 1).m_d_y
puts Date.civil(1908, 1, 10).m_d_y

outputs

1/1/1980
10/1/1980
1/10/1980
1/1/1908
10/1/1908
1/10/1908
Vincent Robert
this actually works, lol, thanks Vincent
Alex Baranosky
A minor variant also works nicely:strftime('%m/%d/%Y').gsub(/0(\d{1})\//, "\\1/")
Alex Baranosky
Yes, Alex. The default counter is {1} so it is not necessary, except for clarity, also "*" is equivalent to {0,} and "+" equivalent to {1,}
Vincent Robert
Or using positive look-ahead, you can do `strftime('%m/%d/%Y').gsub(/0(\d)(?=\/)/, '\1')`.
kejadlen
A: 

You say that Ruby is throwing a syntax error, so your problem lies before you have even reached the regexp. Probably because you aren't calling strftime on anything. Try:

def m_d_y
  t = Time.now
  t.strftime('%m/%d/%Y').gsub(/0?(\d{1})\/0?(\d{1})\//, $1 + "/" + $2 + "/" )
end

Then replace Time.now with a real time, then debug your regexp.

Ben
I was calling strftime from within the Date class :)
Alex Baranosky
Well then. Not sure where the downvote came from, but whatever.
Ben
+3  A: 
"02/02/1980".gsub(/\b0/, '') #=> "2/2/1980"

\b is a zero-width marker for a word boundary, therefore \b0 cannot have a digit before the zero.

glenn jackman
+2  A: 

Why bother with regex when you can do this?

require "date"

class Date
    def m_d_y
      [mon, mday, year].join("/")
    end
end
Alison R.
nice, thanks...
Alex Baranosky