Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to use C++ regex

📅 2020-Jun-23 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 Archive

C++ has regular expressions (regex) in the STL since C++11. This means we can stop writing complex string manipulating and splitting code we had to write before this. The STL regex comes with several classes to fit many usecases.

Find matches in string

Here is an example of matching a regex to a string and extracting out matching substrings:

#include <iostream>
#include <regex>
using namespace std;

int main()
    const std::string s = "The_batsman_hit_10_runs_in_3_overs";
    const std::regex r("\\w*_(\\d+)_runs_\\w*_(\\d+)_overs.*");
    std::smatch m;

    // Returns true only if the regex matched the input string
    // Matched strings are filled up in smatch.
    if (std::regex_match(s.begin(), s.end(), m, r))
        // m[0] holds entire input string. So skip that and start from 1.
        for (auto i = 1; i < m.size(); ++i)
            std::cout << "Matched: " << m[i] << std::endl;

    return 0;

// This outputs:
// Matched: 10
// Matched: 3

Tried with: GCC 7.5.0 and Ubuntu 18.04