blog, c++,

Regular expressions in modern c++

Jing Chi Jing Chi Follow Aug 07, 2019 · 1 min read
Regular expressions in modern c++
Share this

Regular expression allows you to use wildcards and patterns to search and replace characters in strings. In principle, you can do the following operations with regular expressions:

  • Match the whole input against a regular expression
  • Search for patterns that match a regular expression
  • Tokenize a string according to a token separator specified as a regular expression
  • Replace in the first or all subsequences that match a regular expression

Here is a simple example to extract specified part in string using regex_match:

#include <iostream>
#include <regex>

using namespace std;


int main(int argc, char* argv[])
{
    string s = R"(.*(v\d+\.\d+\.\d+).*)";
    cout << "regex: " << s << endl;

    std::regex e(s);
    std::cmatch m;
    std::regex_match(" v12.0.0 EP29", m, e);

    cout << "m.size = " << m.size() << endl;
    cout << "version = " << m[1].str() << endl;

    return 0;
}

Output:

regex: .*(v\d+\.\d+\.\d+).*
m.size = 2
version = v12.0.0

~ TBD ~