编辑:有人可以添加正则表达式解决方案吗?我正在寻找以下正则表达式:
[\(\)!*-+^]
我有一个函数,可以根据我在正文中声明的特殊字符从文本中提取令牌。
该函数有两个问题:
1)。它不打印特殊字符。
2)当两个特殊字符相邻时输出错误
因此我进行了更改,从而解决了问题1(从一些测试结果中可以看出) 但是第二个号码不能解决吗?
注意:我使用的是C ++ 11标准,并且不希望使用boost
示例:鉴于:a+(b*c)
我期望:a,+,(,b,*,c,)
鉴于:a+b
我期望:a,+,b
鉴于:ab+
我期望:ab,+
鉴于:a b+
我期望:a b,+
答案 0 :(得分:1)
这是一个正则表达式解决方案,应该解析您想要的令牌:
void find(std::string str)
{
static const std::regex r(R"(\+|\^|-|\*|!|\(|\)|([\w|\s]+))");
std::copy( std::sregex_token_iterator(str.begin(), str.end(), r, 0),
std::sregex_token_iterator(),
std::ostream_iterator<std::string>(std::cout, "\n"));
}
这里是demo。
这里是explanation。
请注意,如果要进行通用分析,这不是一个好主意。 regex很快就会变得笨拙(如果还没有的话),并且有很多更好的工具可为您完成此操作。
答案 1 :(得分:0)
您不能很好地处理空字符串。在处理空字符串之前,请检查以确保其不为空。
#include <sstream>
#include <string>
#include <vector>
#include <cassert>
using std::string;
using std::stringstream;
using std::vector;
namespace {
// Parse a string into a vector of tokens by special characters.
auto find(string str) -> vector<string> {
auto result = vector<string>{};
auto pos = string::size_type{};
auto last_pos = string::size_type{};
while ((pos = str.find_first_of("+^-*!()", last_pos)) != string::npos) {
// Is there a token before the special character?
if (pos - last_pos > 0) {
result.push_back(str.substr(last_pos, pos - last_pos));
}
last_pos = pos + 1;
// Add the special character as a token.
result.push_back(str.substr(pos, 1));
}
auto last = str.substr(last_pos);
// Is there a trailing token after the last found special character?
if (!last.empty()) {
result.push_back(str.substr(last_pos));
}
return result;
}
// Helper routine.
// Join a vector of strings together using a given separator.
auto join(vector<string> const& v, string sep) -> string {
auto ss = stringstream{};
auto first = true;
for (auto const& s : v) {
if (first) {
ss << s;
first = false;
} else {
ss << sep << s;
}
}
return ss.str();
}
// Helper routine.
// Returns a string representing the tokenized string.
auto check(string s) -> string {
auto v = find(s);
auto result = join(v, ",");
return result;
}
} // anon
int main() {
// Unit tests to check that the string parses and tokenizes into the expected string.
assert(check("a+(b*c)") == "a,+,(,b,*,c,)");
assert(check("a+b") == "a,+,b");
assert(check("ab+") == "ab,+");
assert(check("a b+") == "a b,+");
assert(check("a") == "a");
assert(check("aa") == "aa");
assert(check("+") == "+");
assert(check("++") == "+,+");
assert(check("a+") == "a,+");
assert(check("+a") == "+,a");
assert(check("") == "");
}