1

I've got a regex like this:

    var regex = /(\d\d\/\d\d\/\d\d) (\d\d:\d\d:\d\d): ([^:]+): (.*)/g;

this a regex to read the string below and divide it up into several object properties

    27/02/14 23:45:01: Tom: Ja

With a little help of the regex above, I'm creating an object via this code:

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

Sometime the date doesn't look like dd/mm/yy but rather like dd-mm-yyyy or dd-mm-yy.

Whichever is the good match I want to parse that into the date property. but when adding multiple regex to match[1] the code seems to fail.

1
  • So what are you asking for? An expression that matches dd/mm/yy, dd-mm-yyyy and dd-mm-yy? Commented Mar 1, 2014 at 21:12

1 Answer 1

3

If I understand correctly, your code works when the date is always formatted the same, and you want to be able to accept different formats of dates.

Try this:

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

The above regular expression should accept either a forward slash or dash (by saying [\/-]), and then for the year, accept 2 or 4 digits (by saying \d{2,4}).

Edit

A commenter below made a good suggestion. If you want to make sure the delimiter is the same in both cases, you can do this instead:

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

Just take note, though, that the first delimiter is now a match, so you'll have to adjust your code that creates your object. match[2] will now be the delimiter, so you'll have to do something like this:

var match;
while( match = regex.exec(chat)) {
    messages.push({
        date: match[1],
        time: match[3],
        name: match[4],
        message: match[5]
   });
}
Sign up to request clarification or add additional context in comments.

2 Comments

Technically this would match dd/mm-yy as well (even though such input is probably very unlikely). To match the same delimiter in both cases, you could use a capture group and a backreference instead: (\d\d([\/-])\d\d\2\d{2,4}) (but then the rest of the code would have to be adjusted as well).
I don't know if it's the regex, but this seems to return an empty array. If the date format is dd/mm/yy it does return a proper one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.