正则表达式使用提升令牌迭代器在单引号和括号之间提取值

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

本文关键字:之间 提取 单引号 迭代器 令牌 正则表达式      更新时间:2023-10-16

我有一个这样的值:

Supoose 我有一个字符串:

s = "server ('m1.labs.teradata.com') username ('u'se)r_*5') password('uer 5')  dbname ('default')";

我需要提取

  • 令牌 1 :'m1.labs.teradata.com'
  • 令牌 2 :'u'se)r_*5'
  • 令牌3 :'uer 5'

我在 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;

如果您不希望字符串中包含符号',那么'[^']+'将匹配您的需求:

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

现场示例 结果:

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

如果不需要单引号作为匹配的一部分,请将代码更改为:

regex re("'([^']+)'");
sregex_token_iterator i(s.begin(), s.end(), re, {1});

另一个活生生的例子

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

此字符串的正确正则表达式是

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

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