Skip to content Skip to sidebar Skip to footer

Regular Expression To Only Grab Date

I have a solution for my question, but I'm trying to get better at regex especially in javascript. I just wanted to bring this to the community to see if I could write this in a be

Solution 1:

Anytime you have parenthesis in your regex, the value that matches those parenthesis will be returned as well.

  • time[0] is what matches the whole expression
  • time[1] is what matches ([\d]{4}), i.e. the year
  • time[2] is what matches the first ([\d]{2}), i.e. the month
  • time[3] is what matches the second ([\d]{2}), i.e. the date

You can't change this behavior to remove time[0], and you don't really want to (since the underlying code is already generating it, removing it wouldn't give any performance benefit).

If you don't care about getting back the value from a parenthesized expression, you can use (?:expression) to make it non-matching.

Solution 2:

I don't think that you can do that but you can do

var myregexp = /(^\d{4})-(\d{2})-(\d{2})/g;
var match = myregexp.exec(subject);
while (match != null) {
    for (var i = 1; i < match.length; i++) {
        // matched text: match[i]
    }
    match = myregexp.exec(subject);
}

And then just loop from the index 1. The first item in the array is a match and then the groups are children of that match

Post a Comment for "Regular Expression To Only Grab Date"