Linux 拨号vps windows公众号手机端

C++中regex如何匹配括号

lewis 9年前 (2016-12-18) 阅读数 8 #程序编程
文章标签 c++

在C++中,可以使用正则表达式来匹配括号。下面是一个示例代码,用于匹配包含括号的字符串:

#include <iostream>
#include <regex>

int main() {
    std::string str = "This is a (sample) string with (parentheses)";

    std::regex regex("\\([^()]*\\)");
    std::smatch match;

    while (std::regex_search(str, match, regex)) {
        for (auto m : match) {
            std::cout << m << std::endl;
        }
        str = match.suffix().str();
    }

    return 0;
}

在上面的代码中,我们定义了一个正则表达式 \\([^()]*\\) 来匹配括号内的内容。然后我们使用 std::regex_search 函数来查找字符串中满足正则表达式的部分,并使用 std::smatch 对象来保存匹配的结果。最后输出匹配到的内容。

注意,正则表达式中的 ( ) 需要转义为 \\( \\),以保证它们被当作普通字符处理,而不是分组符号。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门