Tutorial :Regular Expression to only grab date



Question:

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 better way.

So, I get a datetime string that comes from .net and I need to extract the date from it.

Currently what I have is:

var time = "2009-07-05T00:00:00.0000000-05:00".match(/(^\d{4}).(\d{2}).(\d{2})/i);  

As I said, this works, but I was hoping to make it more direct to only grab the Year, month, day in the array. What I get with this is 4 results with the first being YYYY-MM-DD, YYYY, MM, DD.

Essentially I just want the 3 results returned, not so much that this doesn't work (because I can just ignore the first index in the array), but so that I can learn to use regex a bit better.


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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »