在C++中,可以使用正则表达式来匹配括号
在C++中,可以使用正则表达式来匹配括号。下面是一个示例代码,用于匹配包含括号的字符串:
#include<iostream>
#include<regex>
intmain(){
std::stringstr="Thisisa(sample)stringwith(parentheses)";
std::regexregex("\\([^()]*\\)");
std::smatchmatch;
while(std::regex_search(str,match,regex)){
for(autom:match){
std::cout<<m<<std::endl;
}
str=match.suffix().str();
}
return0;
}
在上面的代码中,我们定义了一个正则表达式\\([^()]*\\)
来匹配括号内的内容。然后我们使用std::regex_search
函数来查找字符串中满足正则表达式的部分,并使用std::smatch
对象来保存匹配的结果。最后输出匹配到的内容。
注意,正则表达式中的()
需要转义为\\(\\)
,以保证它们被当作普通字符处理,而不是分组符号。
版权声明
本文仅代表作者观点,不代表博信信息网立场。