如何查找输入日期模式是红宝石或红宝石中的破折号或斜杠或空格



当输入日期为mm-dd-yyyymm/dd/yyyymm dd yyyy时,根据我需要格式化自己的模式。如何找到输入日期是哪种模式?在红宝石/红宝石/瓦蒂尔。以下是红宝石黄瓜代码

Then(/^I see correct (.*) on the form$/) do |mdate|
mdate1 = Date.strptime(mdate,"%m-%d-%Y").strftime("%a %b %d %Y 00:00:00 GMT+0000")
puts "parsing output1 is #{mdate1}"

这里mdate可以是如上所述的任何模式,目前strptime仅适用于一种模式。如果需要为其他模式工作,如何进行?

正则表达式匹配和大小写语句

如果您的问题只是关于如何将您描述的数据与 Ruby 中的正则表达式匹配,您可以使用如下模式:

input_date =~ %r"bd{1,2}([-/ ])d{1,2}1d{4}b"

但是,匹配的有效性将取决于数据集的质量。它有很多方法可能无法匹配或匹配非日期数据。您必须非常了解您的数据,才能制作出一个有用但极简的正则表达式,该表达式仅与您想要的内容匹配。

另一方面,如果您的问题是关于哪种模式匹配,那么:

input_date =~ %r"bd{1,2}([-/ ])d{1,2}1d{4}b"
# print the format based on delimiter used
case input_date.scan(%r"[-/ ]").first
when "/" then p "mm/dd/yyyy"
when "-" then p "mm-dd-yyyy"
when " " then p "mm dd yyyy"
end

您可以根据需要调整操作,例如为 Date#strptime、DateTime#strftime 定义模式、设置变量或调用一个或多个方法来制作或格式化日期对象。不过,这绝对应该让你指向正确的方向。

通过将字符串与以下正则表达式匹配,将保存分隔符字符以捕获组 1。

/(?<!d)d{2}([- /])d{2}1d{4}(?!=d)/

启动引擎!

由于您将尝试将匹配的字符串转换为Date对象,因此您将在那时找到它是否为有效日期。因此,正则表达式无需将月份的可能性限制为 01-12 或天数限制为 01-31;d{2}就足够了。

Ruby 的正则表达式引擎执行以下操作。

(?<!d)   : use a negative lookbehind to assert the previous character
is not a digit
d{2}     : match 2 digits
([- /])  : match a character in the character class and save to
capture group 1
d{2}     : match 2 digits
1        : match the content of capture group 1
d{4}     : match 4 digits
(?!=d)   : use a negative lookahead to assert the next character
: is not a digit

最新更新