Regex to extract value between a single quote and parenthesis using boost token iterator

吃可爱长大的小学妹 提交于 2019-12-13 10:33:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!