-
September 5th, 2014, 09:23 AM
#1
regx to parse key=value pairs.
I want to parse a list of key=value pairs separated by '&'.
I thought a regex would be a good fit.
input string:
key1=value1&key2=value2&key3=value3& ... &keyn=valuen
Code:
std::cmatch res;
std::regex reList("([^=]*)"
"="
"([^&]*)"
"(?:"
"&"
"([^=]*)"
"="
"([^&]*)"
")*");
if (std::regex_match(input, res, reList))
{
//match
}
the above string matches,
but the captures don't quite work. With the above I get only 4 captures, the first key and value pair.
And the last key and value pair, but none of the ones in between.
I can understand why it works like this, but I'm wondering if there's somethign I'm missing to get it to return a variable amount of captures.
-
September 5th, 2014, 10:46 AM
#2
Re: regx to parse key=value pairs.
I don't think regex supports "variadic" capture groups ( at least, it would be new to me ). What I'd do is use regex_search or regex_(token_)iterator instead:
Code:
#include <iostream>
#include <algorithm>
#include <regex>
int main()
{
std::string input("a0=b0&a1=b1&a2=b2&a3=b3&a4=b4");
std::regex reList("([^=]*)=([^&]*)&?");
std::for_each( std::sregex_iterator( input.begin(), input.end(), reList ), std::sregex_iterator(),
[]( std::smatch const& match ){ std::cout << match[1] << "=" << match[2] << "\n"; } );
}
prints
Code:
a0=b0
a1=b1
a2=b2
a3=b3
a4=b4
-
September 5th, 2014, 03:02 PM
#3
Re: regx to parse key=value pairs.
yes, I know I can do the sample code by splitting it into multiple subsequent match calls.
The problem is that it's actually a much more complex regex than in this particular sample. with 3 nested levels of repetition and conditionals making it quite unsuited to splitting up like this. I simplified the problem for posting here. So was really hoping that there's a way to get the single regex to do this.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|