我有一个数学表达式字符串,需要用空格替换括号和其中的所有内容。我在 Visual Studio Express 2012 中完成。
输入=>输出的例子:
"(a+b)*c+(x+y)" => " *c+ "
"a+b" => "a+b"
"(a+b)" => " "
我有代码,可以替换我需要的东西,但它也可以替换除 +
之外的所有内容:
#include <iostream>
#include <string>
#include <regex>
std::string foo(std::string input) {
std::string output;
std::regex r("\\([^()]+\\)|(([a-z]|\\*)+)");
std::smatch m;
while (std::regex_search(input, m, r)) {
output += m.prefix();
output += std::string(m[0].length(), ' '); //here finded parts is replacing
input = m.suffix();
}
output += input;
return output;
}
void test(const std::string &in, const std::string &expected_out) {
std::string real_out = foo(in);
if (real_out == expected_out) {
std::cout << "PASS" << std::endl;
} else {
std::cout << "FAIL: got \"" << real_out << "\" instead of \"" <<
expected_out << "\"" << std::endl;
}
}
int main() {
test("", "");
test("a", " ");
test("a*b*c", " ");
test("a+b", " + ");
test("(a+b*c)+x*y", " + ");
test("(a+b*c)+x+y", " + + ");
test("a+b*c+(x+y)", " + + ");
system ("pause");
return 0;
}
其实我只需要修正正则表达式就可以了。
由于标准正则表达式无法处理嵌套结构,我必须了解一些关于 tusk 的细节。所以,你可以忽略这个选项。
最佳答案
[^\n](?=(?:[^(\n]*\))|((?:[^()\n]*\([^()\n]*\))*[^\(\n]*\)))|\)
试试这个。查看演示。用空格
替换。
关于C++。如何使用 std::regex 替换括号(和括号)内的任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27541992/