简体   繁体   English

使用gsub的Ruby正则表达式

[英]Ruby regular expression using gsub

Hi I'm new to Ruby and regular expressions. 嗨,我是Ruby和正则表达式的新手。 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" 我正在尝试使用正则表达式从格式为“ 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. 您可以简单地删除以斜杠结尾的部分中的0。

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)/ 尝试/(?<!\\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 正则表达式: (^|(?<=/))0

Replacement: '' 替换: ''

You say that Ruby is throwing a syntax error, so your problem lies before you have even reached the regexp. 您说Ruby抛出语法错误,所以您的问题就在您到达正则表达式之前。 Probably because you aren't calling strftime on anything. 可能是因为您没有在任何东西上调用strftime 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. 然后用实时替换Time.now,然后调试您的正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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