2014-12-10 91 views
-1

你好,我想做自动填充匹配这种格式"HH:MM"。 我只想检查这个正则表达式/^(0[1-9]|1[012]):[0-5][0-9]$/,但不知道如何匹配正则表达式子字符串。我看过维基百科和一些网站,找不到修饰符来检查'subregex'。这个选项不存在吗?我终于用下面的代码解决了这个问题,但是这个数组当然可以以编程方式生成,所以应该已经有我正在寻找的解决方案。或者它不存在,我应该写它?只匹配subregex,属于正则表达式的一部分

patterns = [ /./, /^[0-9]$/, /^(0?[1-9]|1[012])$/, /^(0[1-9]|1[012]):$/, /^(0[1-9]|1[012]):[0-5]$/, /^(0[1-9]|1[012]):[0-5][0-9]$/] 
unless patterns[newTime.length].test(newTime) 

    newTime = newTime.substring(0, newTime.length - 1) 
+0

嗨,试试这个链接:http://stackoverflow.com/questions/7536755/regular-expression-for-matching-hhmm-time-format – 2014-12-10 21:41:58

+0

@MirekSurma感谢链接,但我的正则表达式是有效的。这只是为自动填充器找到'subregex'。 – Machiaweliczny 2014-12-10 22:01:37

+0

好吧,让你的字符串匹配这个:(0 [1-9] | 1 [012]):([0-5] [0-9])并获得第2和第3个结果成员? – 2014-12-10 22:09:40

回答

0

你可能会完成同样的事情更有效率。
将正则表达式组合为级联可选表单,然后使用匹配长度,子串
和模板自动完成时间。

伪代码(不知道JS太好)和真正的正则表达式。

# pseudo-code: 
# ------------------------- 
# input = ....; 
# template = '00:00'; 
# rx = ^(?:0(?:[0-9](?::(?:[0-5](?:[0-9])?)?)?)?|1(?:[0-2](?::(?:[0-5](?:[0-9])?)?)?)?)$  
# match = regex(input, rx); 
# input = input + substr(template, match.length(), -1); 


^  
(?: 
     0 
     (?: 
      [0-9] 
      (?: 
       : 
       (?: 
        [0-5] 
        (?: [0-9])? 
       )? 
      )? 
    )? 
    | 
     1 
     (?: 
      [0-2] 
      (?: 
       : 
       (?: 
        [0-5] 
        (?: [0-9])? 
       )? 
      )? 
    )? 
) 
$ 
+0

在'input.match(/ /)'中放置正则表达式,虽然我不明白OP想要做什么。 – nhahtdh 2014-12-11 02:33:21