header_utils
Loading...
Searching...
No Matches
regex.h
1
4
5#pragma once
6
7#include <regex>
8#include "functional.h"
9
11{
12 // Shamelessly stolen from https://stackoverflow.com/a/37516316
13
16
17 using svmatch = std::match_results<std::string_view::const_iterator>;
18
19 template<class BidirIt, class UnaryFunction>
20 [[nodiscard]] std::string regex_replace(BidirIt&& first, BidirIt&& last, const std::regex& re, UnaryFunction&& f)
21 {
22 std::string s;
23
24 typename std::match_results<BidirIt>::difference_type positionOfLastMatch = 0;
25
26 auto endOfLastMatch = first;
27 std::for_each(std::regex_iterator<BidirIt>{first, last, re}, {}, [&](const std::match_results<BidirIt>& match) {
28 auto positionOfThisMatch = match.position(0);
29 auto diff = positionOfThisMatch - positionOfLastMatch;
30
31 auto startOfThisMatch = endOfLastMatch;
32 std::advance(startOfThisMatch, diff);
33
34 s.append(endOfLastMatch, startOfThisMatch);
35 s.append(f(match));
36
37 auto lengthOfMatch = match.length(0);
38
39 positionOfLastMatch = positionOfThisMatch + lengthOfMatch;
40
41 endOfLastMatch = startOfThisMatch;
42 std::advance(endOfLastMatch, lengthOfMatch);
43 });
44
45 s.append(endOfLastMatch, last);
46
47 return s;
48 }
49
50 template<class UnaryFunction>
51 [[nodiscard]] std::string regex_replace(std::string_view s, const std::regex& re, UnaryFunction&& f)
52 {
53 return regex_replace(s.cbegin(), s.cend(), re, std::forward<UnaryFunction>(f));
54 }
55
56 template <class BidirIt, class UnaryFunction>
57 void regex_split(BidirIt first, BidirIt last, const std::regex& re, UnaryFunction&& f)
58 {
59 std::for_each(std::regex_token_iterator<BidirIt>{first, last, re, -1}, {}, std::forward<UnaryFunction>(f));
60 }
61
62 template <class UnaryFunction>
63 void regex_split(std::string_view s, const std::regex& re, UnaryFunction&& f)
64 {
65 regex_split(s.begin(), s.end(), re, std::forward<UnaryFunction>(f));
66 }
67
68 [[nodiscard]] inline std::vector<std::string> regex_split(std::string_view s, const std::regex& re)
69 {
70 return resulting([&](std::vector<std::string>& result) {
71 regex_split(s.begin(), s.end(), re, op::push_back_to(result));
72 });
73 }
74
76}
constexpr T resulting(FUNC &&func)
Returns a new T transformed by func.
Definition functional.h:306