简体   繁体   English

正则表达式匹配似乎无法正常工作

[英]regex match doesn't seem to work javascript

I've got a regex.exec() function like this: 我有一个regex.exec()函数,如下所示:

var chat = reader.result;
var regex = /(\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}) (\d\d:\d\d:\d\d): ([^:]+): (.*)/g;
var messages = [];

var match;
while( match = regex.exec(chat)) {
        messages.push({
            date: match[1],
            time: match[2],
            name: match[3],
            message: match[4]
    });
}

match[1] seems to work on almost all dates: dd/mm/yyyy to dd-mm-yy match [1]似乎适用于几乎所有日期:dd / mm / yyyy到dd-mm-yy

However, when the input is in the following format: 但是,当输入采用以下格式时:

22-2-2014 18:37:15: Andre: Moet nog 2,5 aflevering

it outputs an empty array messages 它输出一个空数组messages

I don't really know where this is coming from but I believe it's regex match[1] , because when the input is 28/02/14 00:03:03: Tom: Je gaat nu de afweging maken 我真的不知道这是哪里来的,但我相信它是regex match[1] ,因为当输入为28/02/14 00:03:03: Tom: Je gaat nu de afweging maken

It returns an array of objects just fine. 它返回一个对象数组就好了。

Ps for the ones interested, the reader.result is from the HTML5 filereader API. ps对那些感兴趣的人来说,reader.result来自HTML5 filereader API。

EDIT I've updated the question with a bug in the regex that was found by a commenter. 编辑我已经用评论者发现的正则表达式中的错误更新了问题。 Still, even with the newer regex the input still fails 即使使用更新的正则表达式,输入仍然会失败

Looks like your regex misses the exception for a single digit month. 看起来您的正则表达式错过了一位数月的异常。 try this: 尝试这个:

/(\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}) (\d\d:\d\d:\d\d): ([^:]+): (.*)/g

edit: also built in optional single digit days. 编辑:还内置可选的单位数字天。

Try this regex ( see demo link ) 试试这个正则表达式( 请参阅演示链接

 (\d\d[\/-]\d\d?[\/-]\d{2,4}) (\d\d:\d\d:\d\d): ([^:]+): (.*)

it matches both: 它同时匹配:

22-2-2014 18:37:15: Andre: Moet nog 2,5 aflevering 22-2-2014 18:37:15:安德烈(Andre):Moet nog 2,5 flevering

22-12-2014 18:37:15: Andre: Moet nog 2,5 aflevering 22-12-2014 18:37:15:安德烈(Andre):Moet nog 2,5 flevering

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM