这个正则表达式有什么作用?

时间:2012-11-22 23:48:25

标签: regex

以下正则表达式有何作用?

^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$

特别是\1部分的目的是什么?

3 个答案:

答案 0 :(得分:4)

你应该看看a tutorial。那里几乎没有任何进展(除了你指出的那个\1):

^         # the start of the string
\d        # a digit
{1,2}     # 1 or 2 of those
(         # start the first subpattern, which can later be referred to with \1
  \-      # a literal hyphen (there is no need for escaping, but it doesn't hurt)
|         # or
  \/      # a literal slash
|         # or
  \.      # a literal period
)         # end of subpattern
\d{1,2}   # one or two more digits
\1        # the exact same thing that was matched in the first subpattern. this
          # is called a backreference
\d{4}     # 4 digits
$         # the end of the string

即。这断言输入字符串恰好包含格式ddmmyyyy(或者也可能是mmddyyyy)的一个日期,不多也不少,包含可能的分隔符.-/(以及一致的分隔符用法)。请注意,它无法确保正确的日期。月份和日期可以是0099

注意 \d的确切含义取决于您正在使用的正则表达式引擎和文化。 通常表示[0-9](任何ASCII数字)。但是,例如在.NET中,它也可以表示“任何表示数字的Unicode字符”。

答案 1 :(得分:3)

  1. ^字符串开头
  2. \d{1,2}匹配1或2位数字(0-9)
  3. (\-|\/|\.)匹配“ - ” OR “/” OR “。”
  4. \d{1,2}再次匹配1或2位数字(0-9)
  5. \1反向引用。匹配第3组中该组捕获的同一角色的另一个实例
  6. \d{4}匹配4位数字
  7. $字符串结尾
  8. 这将匹配以下格式的日期。请注意,ddmmyyyy范围未被检查,因此日期可能仍然无效。

    d-m-yyyy
    d/m/yyyy
    d.m.yyyy
    

    d& m可以是1 2位数。

答案 2 :(得分:1)

匹配:

  • 一位或两位数
  • 短划线,斜线或句号
  • 一位或两位数
  • 另一个分隔符就像前一个
  • 四位数

\1是对第一组匹配的值的反向引用,即(\-|\/|\.)

例如:

2-14-2003
99.99.9999
1/2/0001
相关问题