Regex Search Basic

Here is the problem: we are looking for Date within some log text. Cannot use string::find() because we don’t know exactly what the data is. We only know the pattern of the string of Data: MM-DD-YYYY, month and day can have one or two digits, year has four, and they are separated by two hyphens (-), i.e. 1-31-2010, 12-1-2011.

Boost.Regex is useful in this case. regex_search() can search the text base on specific expression. “\\d{1,2}-\\d{1,2}-\\d{4}” means any string that consists of “either 1 or 2 numbers a hyphen either 1 or 2 numbers a hyphen four numbers”. Here is the search:

std::string::const_iterator start, end;
 start = log_text.begin();
 end = log_text.end();
 static const boost::regex expression("\\d{1,2}-\\d{1,2}-\\d{4}");
boost::match_results<std::string::const_iterator> what;
 while(regex_search(start, end, what, expression, boost::match_extra))
 {
cout<<what[0]<<endl;
 start = what[0].second;
 }
Advertisements

Leave a comment

Filed under C++

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