( ) | (1). 在被修饰匹配次数的时候,括号中的表达式可以作为整体被修饰 |
获取()中表达式匹配到的内容
Java
String text = "token=abcde";
Pattern pattern = Pattern.compile("token=(.+)");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
可以通过调用 matcher 对象的 groupCount 方法来查看表达式有多少个分组。groupCount 方法返回一个 int 值,表示matcher对象当前有多个捕获组。
还有一个特殊的组(group(0)),它总是代表整个表达式。该组不包括在 groupCount 的返回值中。
C++
#include <regex>
regex_match(s,re) 目标字符串s和正则表达式re是否完全匹配
regex_search(s,match_result,re) 目标字符串s是否存在某个子串与正则表达式re匹配
regex_replace(s,re,s1) 用s1替换目标字符串s中与正则表达式re匹配的子串
注意与一般应用正则表达式不同,这里的转义符号要用“\\”
int main(){
//第一种存储方式
//match_results<string::const_iterator> result;
//第二种存储方式
smatch result;
//文本数据
string str="1994 is my birth year 1994";
//正则表达式
string regex_str("\\d{4}");
regex pattern1(regex_str,regex::icase);
//迭代器声明
string::const_iterator iter = str.begin();
string::const_iterator iterEnd= str.end();
string temp;
//正则查找
while (std::regex_search(iter,iterEnd,result,pattern1))
{
temp=result[0];
cout<<temp<<endl;
iter = result[0].second; //更新搜索起始位置
}
//正则匹配
string regex_str2("(\\d{4}).*");
regex pattern2(regex_str2,regex::icase);
if(regex_match(str,result,pattern2)){
cout<<result[0]<<endl;
cout<<result[1]<<endl;
}
//正则替换
std::regex reg1("\\d{4}");
string t("1993");
str = regex_replace(str,reg1,t); //trim_left
cout<<str<<endl;
return 0;
}