正则表达式匹配下面的日期格式 - Regular Expression to match the following Date Format

- 此内容更新于:2015-12-20
主题:

我有一个正则表达式来匹配日期格式或我能匹配Sep.2315&9月23的15但不是Sep2315如何编写正则表达式匹配的空间,没有空间吗?

原文:

I have a regex to match the date formats Sep.23'15 or Sep 23'15 or Sep23'15

[a-zA-Z]{3}[. ]\d{2}'\d{2}

I am able to match Sep.23'15 & Sep 23'15 but not Sep23'15

How to write the regex to match with space and without space ?

网友:使用。答:

(原文:Use ? for [. ]. Answer: [a-zA-Z]{3}[. ]?\d{2}'\d{2})

楼主:谢谢,工作正常。@Tushar

(原文:Thanks, Working Fine. @Tushar)

解决方案:
我建议匹配一个点(可选),然后使用量词,而不是应用于空间:印度央行提出的这个正则表达式也会处理格式像(一个点和空间(s)月和天'year)。正则表达式解释:-3ASCII字母-1或0点0个或多个常规空间(,或者,或者建议根据正则表达式的味道,如果你只需要匹配水平空白)-2位++2位数。看到演示
原文:

I suggest matching a dot (optionally) and then use * quantifier instead of the ? suggested by Tushar applied to a space:

[a-zA-Z]{3}\.?[ ]*\d{2}'\d{2}
           ^^^^^^^

This regex will also handle format like Sep. 23'15 (with a dot and a space(s) between the month and the day'year).

Regex explanation:

  • [a-zA-Z]{3} - 3 ASCII letters
  • \.? - 1 or 0 dots
  • [ ]* - zero or more regular spaces (\h, or \p{Zs}, or [[:blank:]] are recommended depending on the regex flavor if you only need to match horizontal whitespace)
  • \d{2}'\d{2} - 2 digits + ' + 2 digits.

See demo

网友:你使用(不正确的,因为它允许有效),但(正确的)在你的演示……为什么?

(原文:you use * (incorrect, as it allows Sep.......23'15 as valid) but ? (correct) in your demo... why?)

网友:@LuisColorado:我很好奇自己为什么发生。我考虑了你的话,重新考虑我的答案更好地表达我的方法。

(原文:@LuisColorado: I am curious why that happened myself. I took into account your remark and reconsidered my answer to better express my approach.)

解决方案:
你可以使用下面的正则表达式:
原文:

You can use the following regex:

[A-Za-z]{3}[\.\s]?\d{1,2}\'\d{2}
网友:一个点在一个字符类已经匹配一个文字符号,没有必要逃避它。此外,OP可能不想匹配任何空白(也匹配换行符号)。

(原文:A dot inside a character class already matches a literal . symbol, no need escaping it. Also, OP might not want to match any whitespace (\s also matches newline symbols).)