在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 对象来保存匹配的结果。最后输出匹配到的内容。
注意,正则表达式中的 ( ) 需要转义为 \\( \\),以保证它们被当作普通字符处理,而不是分组符号。




