duong_dajgja
duong_dajgja

Reputation: 4276

C++ regex pattern to match datetime for both Windows and Posix systems

I would like to match datetime in a string like this:

Blah blah blah 2015/11/03 20:25:50 blah blah blah

My application must work well on both Windows and Linux. I am going to use std::tr1 for Windows version and regex (regex.h) for Linux version. Now I need to write a regex pattern that can work with both std::tr1 on Windows and regex on Linux. Please help!

Update:

This works for me on Windows, but it doesn't work on Linux

"(\\d{4})\\/(\\d{2})\\/(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})"

Upvotes: 0

Views: 2186

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626893

You may use the following regex in both Windows (C++ regex module) and Linux (regex.h module):

([0-9]{4})/([0-9]{2})/([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})

Remove the groups if you are not interested in the captured texts.

Here is a regex.h Linux demo showing that the match is found. And here is the same regex in C++ demo.

The thing is that in regex.h, POSIX BRE regex is used by default, and you need to use REG_EXTENDED flag to use POSIX ERE standard (where you do not need to eascape braces and brackets.)

See this POSIX reference:

BRE: \{m,n\}
ERE: {m,n}
Matches the preceding element at least m and not more than n times. For example, a\{3,5\} matches only "aaa", "aaaa", and "aaaaa". This is not found in a few older instances of regular expressions.

Note that you can use [[:digit:]] instead of [0-9] in POSIX.

Upvotes: 1

Related Questions