在 C++ 中从右到左迭代地从字符串中删除平衡方括号的正则表达式解决方案

Regex solution to remove balanced square brackets from a string from right to left iteratively in C++

提问人:yasara malshan 提问时间:11/17/2023 最后编辑:Ulrich Eckhardtyasara malshan 更新时间:11/17/2023 访问量:59

问:

需要一个 C++ 正则表达式解决方案来迭代地从字符串中删除平衡的 []。 我编写了以下代码,但它没有涵盖确切的要求。

std::string removeSqr(const std::string input)
{
    std::string result = input;
    while (true)
    {
        std::smatch match;
        if (std::regex_search(result, match, std::regex("\\[[^\\[\\]]*\\]$")))
        {
            result = match.prefix().str() + match.suffix().str();
            std::cout << result << std::endl;
        }
        else
        {
             break;
        }
    }
    cout << "final : " << result << endl;
    return result;
}

这适用于以下示例:

给定 => “abc[d]n[r][q]” 然后 => “abc[d]n[r]”, “abc[d]n”

但它不适用于以下情况:

给定 => “abc[d]n[r][][5]” 应为 => “abc[d]n[r][]”, “abc[d]n[r]”, “abc[d]n”

给定 => “abc[[]][]” 应该是 => “abc[[]]”, “abc”

给定 => “abc[[s]5][w]” 应为 => “abc[[s]5]”, “abc”

.

此外,还需要一个直接的正则表达式解决方案。

例如:“ABC[[S]5][W]” -> “ABC”

C++ 正则表达式

评论


答: 暂无答案