开发者

Regular Expressions: Extract Dates From String

开发者 https://www.devze.com 2022-12-10 15:57 出处:网络
Hopefully this won\'t be too difficult, but I\'m no开发者_Go百科t too skilled in regular expressions. I have a string that contains two dates and would like to extract the two dates into an array or s

Hopefully this won't be too difficult, but I'm no开发者_Go百科t too skilled in regular expressions. I have a string that contains two dates and would like to extract the two dates into an array or something using JAVASCRIPT.

Here's my string: "I am available Thursday, October 28, 2009 through Saturday, November 7, 2009"

I would like for the array to be: arr[0] = "Thursday, October 28, 2009" arr[1] = "Saturday, November 7, 2009"

Is this even possible to do?

Thanks for all your help!


You don't need a regular expression for a (mostly) static string like that. How about:

var s = "I am available Thursday, October 28, 2009 through Saturday, November 7, 2009";
var dates = s.split('available')[1].split('through');
trim(dates[0]); // "Thursday, October 28, 2009"
trim(dates[1]); // "Saturday, November 7, 2009"

trim() strips leading + trailing whitespace:

function trim(str) {
    return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}


With just regular expressions, you could only really make it work for very specifc date formats. So this will match your exact words:

var s="I am available Thursday, October 28, 2009 through Saturday, November 7, 2009";
arr=s.match(/(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)[^\d]*\d*, \d*/g);
alert(arr);

But not if someone just typed: "October 28, 2009".


"(Sunday|Monday|Tuesday|etc), (January|February|etc) [1-3]?[0-9], [0-9][0-9][0-9][0-9]", maybe? Syntax might not be exact for Javascript but that should get the idea across. It would have the potential for false positives (January 39th) but trying to account for complex calendar rules in a regexp is a mistake.

0

精彩评论

暂无评论...
验证码 换一张
取 消