本文介绍了避免 cpp 中的空令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
限时送ChatGPT账号..我有一个字符串:
s = "server ('m1.labs.terada')ta') username ('user5') password('user)5') dbname ('default')";
我正在提取参数名称:例如服务器、用户名...、数据库名称.
I am extracting the argument names: such as server, username..., dbname.
为此,我使用以下正则表达式:
To do this I am using the following regex:
regex re("\\(\'[!-~]+\'\\)");
sregex_token_iterator i(s.begin(), s.end(), re, -1);
sregex_token_iterator j;
unsigned count = 0;
while(i != j)
{
string str1 = *i;
cout <<"token = "<<str1<< endl;
i++;
count++;
}
cout << "There were " << count << " tokens found." << endl
为此,我得到的输出是:
For this the output I am getting is :
token = server
token = username
token = password
token = dbname
token =
There were 5 tokens found.
我应该如何避免形成第 5 个令牌.我错过了什么吗?
How shall I avoid the 5th token formed. Am I missing out on anything?
推荐答案
原来在字符串的末尾有一些非单词字符.您可以将它们与 \W*
(零个或多个非单词字符)匹配.由于您的标记仅由单词字符组成,因此您可以使用 \W*
模式安全地包装您的模式:
It turns out there are some non-word chars at the end of the string. You may match them with \W*
(zero or more non-word chars). Since your tokens are only composed of word chars, you may safely wrap your pattern with \W*
pattern:
regex re("\\W*\\(\'[!-~]+\'\\)\\W*");
查看 C++ 在线演示
结果:
token = server
token = username
token = password
token = dbname
There were 4 tokens found.
这篇关于避免 cpp 中的空令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论