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

Getting a matching group into a string doesn't work #275

Closed KOLANICH closed 1 year ago

KOLANICH commented 1 year ago
#include <cstddef>
#include <string>
#include <iostream>

#include <ctre.hpp>

static constexpr auto elRx = ctll::fixed_string{ "([^:]*):(\\w+):([^:]*)" };

int main(int argc, const char **argv) {
    std::string line{"alice :lock: mallory :unlock: bob"};
    std::cerr << "Original string: " << line << std::endl;

    for (auto match: ctre::range<elRx>(line)) {
        std::cerr << 0 << " " << match.get<0>() << std::endl;
        std::cerr << 1 << " " << match.get<1>() << std::endl;
        std::string nameS = std::string{match.get<2>()};
        std::cerr << 2 << " " << match.get<2>() << std::endl;
        std::cerr << "nameS" << " " << nameS << std::endl;
        std::cerr << 3 << " " << match.get<3>() << std::endl;
    }
    return 0;
}
Original string: alice :lock: mallory :unlock: bob
0 alice :lock: mallory 
1 alice 
2 lock
nameS 
3  mallory 
0 :unlock: bob
1 
2 unlock
nameS 
3  bob

My guess is that nameS must be the same as 2.

Tested with Debian clang version 17.0.0 (++20230129100618+fd9f42fad22c-1~exp1~20230129220727.1072)

(clang++ -O3 -std=gnu++2b ./test.cpp -o test)

and g++ (Debian 12.2.0-14) 12.2.0

(g++ -O3 -std=gnu++2b ./test.cpp -o test)

Workaround:

auto nameS = std::string{match.get<2>().to_view()};
Original string: alice :lock: mallory :unlock: bob
0 alice :lock: mallory 
1 alice 
2 lock
nameS lock
3  mallory 
0 :unlock: bob
1 
2 unlock
nameS unlock
3  bob
hanickadot commented 1 year ago

Hi, thank you for report, there is multiple workarounds:

1) the one you mentioned 2) match.get<2>().to_string() 3) std::string(match.get<2>()) (avoid using {} as it using std::initialized_lists and looks anything convertible to char which select operator bool

I made change in latest main, where operator bool is now explicit for captures (not for result tuple type), which fixes it for you.

KOLANICH commented 1 year ago

Thank you for the explaination and for the fix.