问题
I have a value like this:
Supoose I have a string:
s = "server ('m1.labs.teradata.com') username ('u\'se)r_*5') password('uer 5') dbname ('default')";
I need to extract
- token1 :
'm1.labs.teradata.com'
- token2 :
'u\'se)r_*5'
- token3 :
'uer 5'
I am using the following regex in cpp:
regex re("(\'[!-~]+\')");
sregex_token_iterator i(s.begin(), s.end(), re, 0);
sregex_token_iterator j;
unsigned count = 0;
while(i != j)
{
cout << "the token is"<<" "<<*i++<< endl;
count++;
}
cout << "There were " << count << " tokens found." << endl;
return 0;
回答1:
If you do not expect symbol '
inside your string then '[^']+'
would match what you need:
regex re("'[^']+'");
live example Result:
the token is 'FooBar'
the token is 'Another Value'
There were 2 tokens found.
if you do not need single quotes to be part of match change code to:
regex re("'([^']+)'");
sregex_token_iterator i(s.begin(), s.end(), re, {1});
another live example
the token is FooBar
the token is Another Value
There were 2 tokens found.
回答2:
The correct regex for this string would be
(?:'(.+?)(?<!\\)')
https://regex101.com/r/IpzB80/1
来源:https://stackoverflow.com/questions/45192314/regex-to-extract-value-between-a-single-quote-and-parenthesis-using-boost-token