我有这样一个字符串:
std::string input = "This* #is # #just# a *random ##string #*that#
may contain any# char*cters#";
我需要获取所有子字符串:
1) 在字符'#'之间
和
2) 包含字符'*'
结果将是:
" a *random "
"*that"
" char*cters"
我是这样做的:
std::vector<std::string> substrings;
boost::split(substrings, input, boost::is_any_of("#"));
for (int i = 0; i < substrings.size(); i++)
{
if (i != 0 // first and last substring is not between '#' (only from one side)
&& (i != substrings.size() - 1)
&& !substrings[i].empty()
&& substrings[i].find('*') != std::string::npos) // if contain '*' character
{
// Here I've got my result
}
}
它有效,但是否有任何有效的解决方案来做到这一点?
最佳答案
您可以使用 regular expression "#([^#*]*[*][^#]*)#"
提取所有此类字符串。
该表达式描述了您要查找的子字符串的种类:
- 以
#
开头 - 有零个或多个除星号以外的字符,...
- 后跟至少一个星号
- 后跟除
#
之外的零个或多个字符
- 最后是
#
。
关于c++ - 从包含特殊字符的字符串中获取所有子字符串的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22114439/