Table of Contents

C - C++ Strings - Search for patterns in strings

regex.hpp

#pragma once
 
#include <vector>
#include <tuple>
#include <string>
 
// Return a list of the list of submatches of regex in input.
std::vector<std::vector<std::string>> getMatches(std::string input, std::string regex);
 
std::vector<std::string> getFirstMatch(std::string content, std::string pattern);

regex.cpp

#include "regex.hpp"
#include <regex>
 
std::vector<std::vector<std::string>> getMatches(std::string content, std::string pattern)
{
  std::vector<std::vector<std::string>> result;
  std::regex regex(pattern);
 
  std::for_each(std::sregex_iterator(content.begin(), content.end(), regex), std::sregex_iterator(), [&](std::smatch match)
  {
    std::vector<std::string> subMatches;
    for (std::string subMatch : match)
    {
      subMatches.emplace_back(subMatch);
    }
    result.emplace_back(subMatches);
  });
 
  return result;
}
 
 
std::vector<std::string> getFirstMatch(std::string content, std::string pattern)
{
  std::vector<std::string> subMatches;
  std::smatch match;
 
  if (std::regex_search(content, match, std::regex(pattern)))
  {
    for (std::string subMatch : match)
    {
      subMatches.emplace_back(subMatch);
    }
  }
 
  return subMatches;
}

References

https://en.cppreference.com/w/cpp/regex/regex_iterator

https://en.cppreference.com/w/cpp/regex/regex_search