header_utils
Loading...
Searching...
No Matches
regex.h
1
4
5#pragma once
6
7#include <regex>
8
10{
12
13 using svmatch = std::match_results<std::string_view::const_iterator>;
14
15 template<class BidirIt, class UnaryFunction>
16 std::string regex_replace(BidirIt&& first, BidirIt&& last, const std::regex& re, UnaryFunction&& f)
17 {
18 std::string s;
19
20 typename std::match_results<BidirIt>::difference_type positionOfLastMatch = 0;
21 auto endOfLastMatch = first;
22
23 auto callback = [&](const std::match_results<BidirIt>& match) {
24 auto positionOfThisMatch = match.position(0);
26
28 std::advance(startOfThisMatch, diff);
29
31 s.append(f(match));
32
33 auto lengthOfMatch = match.length(0);
34
36
38 std::advance(endOfLastMatch, lengthOfMatch);
39 };
40
41 std::regex_iterator<BidirIt> begin(first, last, re), end{};
42 std::for_each(begin, end, callback);
43
44 s.append(endOfLastMatch, last);
45
46 return s;
47 }
48
49 template<class UnaryFunction>
50 std::string regex_replace(std::string_view s, const std::regex& re, UnaryFunction&& f)
51 {
52 return regex_replace(s.cbegin(), s.cend(), re, std::forward<UnaryFunction>(f));
53 }
54
55 template<class BidirIt, class UnaryFunction>
56 void regex_split(BidirIt first, BidirIt last, const std::regex& re, UnaryFunction&& f)
57 {
58 std::regex_token_iterator<BidirIt> iter(first, last, re, -1);
59 std::regex_token_iterator<BidirIt> end;
60 for (; iter != end; ++iter)
61 f(*iter);
62 }
63
64 template<class UnaryFunction>
65 void regex_split(std::string_view s, const std::regex& re, UnaryFunction&& f)
66 {
67 regex_split(s.begin(), s.end(), re, std::forward<UnaryFunction>(f));
68 }
69
70 inline std::vector<std::string> regex_split(std::string_view s, const std::regex& re)
71 {
72 std::vector<std::string> result;
73 regex_split(s.begin(), s.end(), re, [&result](auto&& m) { result.push_back(m.str()); });
74 return result;
75 }
76
77}
constexpr auto bit_count
Equal to the number of bits in the type.
Definition bits.h:33
std::match_results< std::string_view::const_iterator > svmatch
Shamelessly stolen from https://stackoverflow.com/a/37516316.
Definition regex.h:13