2

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.

6 Answers 6

3
"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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

3 Comments

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

Why bother with regex when you can do this?

require "date"

class Date
    def m_d_y
      [mon, mday, year].join("/")
    end
end

Comments

0

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

"02/02/1980".gsub(/(?<!\d)0(\d)/,$1)
=> "2/2/1980"

2 Comments

Huh? On what Ruby interpreter did you do that? AFAIK (and according regular-expressions.info/lookaround.html) Ruby does not support look-behinds and replacement-interpolation is done through '\1' (including quotes!) instead of $1.
I am not sure with other ruby, but ruby 1.9 support that.
0

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

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

Replacement: ''

1 Comment

Ruby does not support look-behinds. See: regular-expressions.info/lookaround.html
0

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.

2 Comments

I was calling strftime from within the Date class :)
Well then. Not sure where the downvote came from, but whatever.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.