简体   繁体   中英

Ruby regular expression using gsub

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.

"02/02/1980".gsub(/\b0/, '') #=> "2/2/1980"

\\b是单词边界的零宽度标记,因此\\b0不能在零之前有数字。

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

Why bother with regex when you can do this?

require "date"

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

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

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

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

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

Replacement: ''

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM