User Tools

Site Tools


c_-_c_strings:search_for_patterns_in_strings

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

c_-_c_strings/search_for_patterns_in_strings.txt · Last modified: 2021/04/28 10:24 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki