regex_match()
输入年月日,如果符合这种格式:1999/01/12 或 1999/1/12
则分别打印:整个字符串、月份、日期。
#include <iostream>
#include <regex>
#include <format>
#include <string>
using namespace std;
int main(){
//匹配年月日
regex r{ R"((?:\d{4})/(0?[1-9]|1[1-2])/(0?[0-9]|[1-2][0-9]|3[0-1]))" };
while (true) {
cout << "Enter a date (year/month/day) (q=quit): ";
string str;
if (!getline(cin, str) || str == "q") {break;}
smatch m;//储存捕获到的子表达式
if ( regex_match(str, m, r)) {
cout << "Valid date :" << endl;
//m[0]是匹配整个模式的字符串,m[1]是第一个捕获组匹配的子字符串,m[2]是第二个捕获组匹配的子字符串
cout << format("{}\n{}\n{}\n", m[0].str(), stoi(m[1]), stoi(m[2]));
}
else {
cout << " Invalid date !" << endl;
}
}
}
regex_replace()
输入一段代码(包含//风格注释),以@结束。使用正则表达式删除注释。
int main(){
regex r{ "^(.*?)//.*$" };
const string replacement{ "$1" };//匹配第一个捕获组的字符串
while (true) {
cout << "Enter a source code snippet, terminated with @:" << endl;
string str;
if (!getline(cin, str, '@')) {break;}//@为结束字符
cout << regex_replace(str, r, replacement) << endl;
}
}
可以将regex_replace的第四个参数format_no_copy标志,使其不复制不匹配的内容到结果字符串。