Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Supports for PCRE Comment #273

Open
sandwoodK opened this issue Oct 24, 2022 · 2 comments
Open

Supports for PCRE Comment #273

sandwoodK opened this issue Oct 24, 2022 · 2 comments

Comments

@sandwoodK
Copy link

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)

@alexios-angel
Copy link

alexios-angel commented Jul 27, 2024

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

@hanickadot
Copy link
Owner

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants