C++。如何使用 std::regex 替换括号(和括号)内的任何内容?

标签 c++ regex

我有一个数学表达式字符串,需要用空格替换括号和其中的所有内容。我在 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]*\)))|\)

试试这个。查看演示。用空格替换。

https://regex101.com/r/cA4wE0/18

关于C++。如何使用 std::regex 替换括号(和括号)内的任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27541992/

相关文章:

c++ - 将位图作为 Windows 资源加载时,有没有办法保留 BITMAPFILEHEADER?

javascript - 正则表达式匹配可选参数

regex - 命名捕获组中的顺序

python - 仅从以下输出中过滤 'download_url' 的值 - python

regex - 用正则表达式查找替换文件内容

c++ - 使用C++11的线程基类

c++ - 使用 stringstream 处理二进制文件的问题

c++ - 线程特定数据与线程本地存储

c++ - 有什么理由不使用 Boost::shared_ptrs 吗?

PHP 正则表达式匹配字符串中的组