How can I use regex on the back line?
I want to use regex
on the back string
.
I can do the following, but all my sub_match
es are reversed:
string foo("lorem ipsum");
match_results<string::reverse_iterator> sm;
if (regex_match(foo.rbegin(), foo.rend(), sm, regex("(\\w+)\\s+(\\w+)"))) {
cout << sm[1] << ' ' << sm[2] << endl;
}
else {
cout << "bad\n";
}
[ Live example ]
I want to exit:
ipsum lorem
Is there any condition in order to receive support matches that have not been canceled? That is, any out-of-scope condition string
after they match like this:
string first(sm[1]);
string second(sm[2]);
reverse(first.begin(), first.end());
reverse(second.begin(), second.end());
cout << first << ' ' << second << endl;
EDIT:
It was suggested that I update the question to clarify what I want:
Running regex
backwards on string
is not about changing the order of the matches. regex
much more complex, which would be useful to post here, but running it back saves me from looking ahead. This question is about handling auxiliary matches obtained from match_results<string::reverse_iterator>
. I need to get them, as they were at the entrance, here foo
. I dont want to create a temporary string
and run reverse
on it for every subheading. How can I avoid this.
source to share
It's absolutely possible! The key is that a sub_match
inherits frompair<BidirIt, BidirIt>
. Since sub_match
es will be derived from:, match_results<string::reverse_iterator> sm
elements from pair
a sub_match
that inherit from will be string::reverse_iterator
s.
So, for any given sub_match
of sm
you can get the direct access range in front of it second.base()
first.base()
. You don't need to create ranges string
for streams, but you will need to create ostream_iterator
:
ostream_iterator<char> output(cout);
copy(sm[1].second.base(), sm[1].first.base(), output);
output = ' ';
copy(sm[2].second.base(), sm[2].first.base(), output);
Take your heart, although there is a better solution on the horizon! This answer discusses string_literal
with right now no action was taken but they entered the "Evolution Subgroup".
source to share
You can simply change the order in which you use the results:
#include <regex>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string foo("lorem ipsum");
smatch sm;
if (regex_match(foo, sm, regex("(\\w+)\\s+(\\w+)"))) {
cout << sm[2] << ' ' << sm[1] << endl; // use second as first
}
else {
cout << "bad\n";
}
}
Output:
ipsum lorem
source to share