hanickadot / compile-time-regular-expressions

Compile Time Regular Expression in C++
https://twitter.com/hankadusikova
Apache License 2.0
3.22k stars 177 forks source link

feature request for range api (match.position()) #182

Open aaangeletakis opened 3 years ago

aaangeletakis commented 3 years ago

The STL has a match_results::position() function that returns the position of the match in the string. https://www.cplusplus.com/reference/regex/match_results/position/

This could possibly be implemented via subtracting 2 pointers.

const char * str = ...
const char * match = ...
int position = match - str;

Example use

#include <ctre.hpp>
#include <iostream>

const char * input = "123,456,768";
//extern const char * input;

int main(void){
    auto matches = ctre::range<"([0-9]+),?">(input);
    for (auto match: matches) {
        std::cout << "Match found at " << std::string_view{match.get<0>()} << "\n";
        //std::cout << "Position at" << match.position() << "\n";
    }
    return 0;
}

Compiler Explorer

aaangeletakis commented 3 years ago

Turns out you can get the position via a view


#include "ctre.hpp"
#include <iostream>

const char * input = "123,456,768";
//extern const char * input;

int main(void){
    static constexpr ctll::fixed_string pat = "([0-9]+),?";
    auto matches = ctre::range<pat>(input);
    for (auto match: matches) {
        auto view = match.to_view();
        std::cout << view.data() - input << " [" << view << "]\n";
    }
    return 0;
}