compile-time-regular-expressions icon indicating copy to clipboard operation
compile-time-regular-expressions copied to clipboard

Supports for PCRE Comment

Open sandwoodK opened this issue 3 years ago • 2 comments

Even if comments can be stripped-off from a regexp, it would help to pass verbatim some regexp with comments inside directly. To make it crystal clear :

need for support of (?#foo comment)

sandwoodK avatar Oct 24 '22 19:10 sandwoodK

You can still use comments. You just need to remove them with ctre's ctre::split first. See below; The comments are removed at compile time and the regex regex_array it matched against "abc".

#include <array>
#include <iostream>
#include <string_view>
#include <algorithm>
#include <ctre.hpp>

template<typename T, std::size_t items>
constexpr auto join_matches_as_array(const auto& range){
    std::array<T, items> result{};
    std::size_t i = 0;
    for (const auto &m : range) {
        std::copy(m.begin(), m.end(), result.begin()+i);
        i += m.size();
    }
    return result;
}


constexpr auto accumulate_match_sizes(const auto& range){
    std::size_t res = 0;
    for (const auto match : range) {
        res += match.size();
    }
    return res;
}

int main()
{
    constexpr std::string_view inital_regex = R"((?#
        This is a regex comment
    )[a-zA-Z]+(?# 
        Above is my regex
    ))";

    constexpr auto matches = ctre::split<R"(\(\?#[^)]*\))">(inital_regex);

    constexpr std::size_t total_size_of_all_matches = accumulate_match_sizes(matches);
    constexpr auto regex_array = join_matches_as_array<char, total_size_of_all_matches>(matches);
    
    //Print out the resulting regex
    std::cout << '"';
    for(const auto c : regex_array){std::cout << c;}
    std::cout << "\"\n";

    if constexpr (ctre::match<regex_array>("abc")){
        return 1;
    } else {
        return 0;
    }
}

Godbolt link

alexios-angel avatar Jul 27 '24 21:07 alexios-angel

Ok WOW, this is beatiful! And so meta. I love it! ❤️

hanickadot avatar Jul 28 '24 05:07 hanickadot