Capturing data using RegExp Backreferences

Quite often you need to capture data from a string. For example when translating a formatted date into a date object. The following example shows one way you can do that in Javascript.

// String to parse
var dateString = "Mar 27 2008 1:46PM";

// Define the pattern, including capturing brackets
// ^ - Start of string
// (\w{3}) - Three letters : "Mar"
// ([0-9]{1,2}) - One or two numbers : "27"
// ([0-9]{4}) - Four numbers : "2008"
// ([0-9]{1,2}) - One or two numbers : "1"
// : - Colon
// ([0-9]{2}) - Two numbers : "46"
// (\w{2}) - Two letters : "PM";
// $ - End of string;
var format =
        /^(\w{3}) ([0-9]{1,2}) ([0-9]{4}) ([0-9]{1,2}):([0-9]{2})(\w{2})$/i;

// Specify which bracket pairs have which meanings
// This is mostly just to make the code readable below
var parts = {
        month : "$1",
        day : "$2",
        year : "$3",
        hour : "$4",
        minute : "$5",
        half : "$6" };

// Define key to translate month names to numbers
var months = {
        Jan:1,
        Feb:2,
        Mar:3,
        Apr:4,
        May:5,
        Jun:6,
        Jul:7,
        Aug:8,
        Sep:9,
        Oct:10,
        Nov:11,
        Dec:12 };

// Execute the RegExp
format.exec( dateString );

// Pull a few captured values out of global RegExp object
var hour = parseInt( RegExp[parts.hour], 10 );
var half = RegExp[parts.half];
hour = ( half == "AM" && hour == 12 ) ? 0 : hour;
hour += ( half == "PM" && hour != 12 ) ? 12 : 0;

// Create a date object and set the captured values
var d = new Date();
d.setUTCFullYear(
	RegExp[parts.year],
	( months[ RegExp[parts.month] ] - 1 ),
	RegExp[parts.day] );
d.setUTCHours( hour );
d.setUTCMinutes( RegExp[parts.minute] );
d.setUTCSeconds(0);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: