Regular expression to extract value between single quote and parenthesis using iterator with token escalation

I have a value similar to this:

Supoose I have a line:

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
source share
2 answers

If you do not expect the character ' inside your string, then '[^']+' will match what you need:

 regex re("'[^']+'"); 

living example Result:

 the token is 'FooBar' the token is 'Another Value' There were 2 tokens found. 

if you don't need single quotes to be part of the matching change code:

 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
source

The correct regular expression for this line would be

 (?:'(.+?)(?<!\\)') 

https://regex101.com/r/IpzB80/1

0
source

Source: https://habr.com/ru/post/1270134/


All Articles