2016-10-20 61 views
2

我有以下的输入字符串:JavaScript的正则表达式 - 不能得到正确的模式

02:00:00_03:00:[email protected] 

或本:

02:00:00_03:00:[email protected] 

我想写一个javascript正则表达式将匹配两者。 “mtwrf”是可选的...它可能会或可能不会出现在输入中。

我一直在使用这个网站来测试: http://www.regexpal.com/

这种模式:

(\d\d\:\d\d:\d\d\_){2}([mtwrfsn\_]*)([\w\d]+\@?[\w\d\.]+) 

似乎使用输入字符串按照regexpal.com网站的工作:

02:00:00_03:00:[email protected] 

但是,当我将它插入我的代码时...它不匹配/找到“02:00:00”。

这里是我的javascript代码:

 var pattern = /(\d\d\:\d\d:\d\d\_){2}([mtwrfsn\_]*)([\w\d]+\@?[\w\d\.]+)/; 
      if (rules_array[i].length > 0) { 
        searchval = rules_array[i].match(pattern); 
      } 
      console.log(searchval); 

和输出我得到的是这样的:

[ '02:00:00_03:00:[email protected]', 
    '03:00:00_', 
    '', 
    '[email protected]', 
    index: 0, 
    input: '02:00:00_03:00:[email protected]' ] 

我想我应该会看到这样的事情,而不是:

[ '02:00:00_03:00:[email protected]', 
    '02:00:00_', 
    '03:00:00_', 
    '[email protected]', 
    index: 0, 
    input: '02:00:00_03:00:[email protected]' ] 

能你看到我的错误/问题在哪里? 谢谢。

+1

当使用重复捕获组时,每次组匹配时,捕获的该组内容将被替换。 –

+0

我推荐[regexr.com](http://regexr.com/):'((\ d {2}:){2} \ d {2} _){2}。* @。*。com' –

+0

@SebastianProske哦......那么你的意思是我应该摆脱对我的模式中的“{2}”之类的引用? – Happydevdays

回答

0

您遇到的问题与重复捕获组有关,请参阅How to capture an arbitrary number of groups in JavaScript Regexp?

然而,对于你的情况下,解决方案是只拼写出捕获组用于所述第二时间值:

var pattern = /(\d\d\:\d\d:\d\d_)(\d\d\:\d\d:\d\d_)([mtwrfsn_]*)(\w+?[\w.]+)/; 
 
var searchval = "02:00:00_03:00:[email protected]".match(pattern); 
 
console.log(searchval);

得到

[ 
    "02:00:00_03:00:00_mtw_1234", 
    "02:00:00_", 
    "03:00:00_", 
    "mtw_", 
    "1234" 
] 

该图案可以是进一步缩短,只需注意[\w\d] = \w\w matc hes数字以及\d