字符规则在C++11中引入了正则表达式。
先来了解一下这个字符的含义吧。
| 字符 | 描述 |
|---|---|
| 转义字符 | |
| $ | 匹配字符行尾 |
| * | 匹配前面的子表达式任意多次 |
| + | 匹配前面的子表达式一次或多次 |
| ? | 匹配前面的子表达式零次或一次 |
| {m} | 匹配确定的m次 |
| {m,} | 匹配至少m次 |
| {m,n} | 最少匹配m次,最大匹配n次 |
| 字符 | 描述 |
|---|---|
| . | 匹配任意字符 |
| x|y | 匹配x或y |
| [xyz] | 字符集合,匹配包含的任意一个字符 |
| [^xyz] | 匹配未包含的任意字符 |
| [a-z] | 字符范围,匹配指定范围内的任意字符 |
| [^a-z] | 匹配任何不在指定范围内的任意字符 |
regex_match头文件:#include
全文匹配,即要求整个字符串符合匹配规则,返回true或false
匹配“四个数字-一个或俩个数字”#include匹配邮箱 “大小写字母或数字@126/163.com”#include using namespace std; int main() { string str; cin >> str; //d 表示匹配数字 {4} 长度4个 d{1,2}表示匹配数字长度为1-2 cout << regex_match(str, regex("\d{4}-\d{1,2}")); return 0; }
int main()
{
string str;
cout << "请输入邮箱:" << endl;
while (cin >> str)//匹配邮箱
{
if (true == regex_match(str, regex("[a-zA-Z0-9]+@1(26|63)\.com")))
{
break;
}
cout << "输入错误,请重新输入:" << endl;
}
cout << "输入成功!" << endl;
return 0;
}
regex_search
搜索匹配,即搜索字符串中存在符合规则的子字符串。
用法一:匹配单个#include用法二:匹配多个#include #include using namespace std; int main() { string str = "hello2019-02-03word"; smatch match;//搜索结果 regex pattern("(\d{4})-(\d{1,2})-(\d{1,2})");//搜索规则 ()表示把内容拿出来 if (regex_search(str, match, pattern)) { //提取 年 月 日 cout << "年:" << match[1] << endl; cout << "月:" << match[2] << endl; cout << "日:" << match[3] << endl; //下标从1开始 下标0存的是符合这个搜索规则的起始位置和结束位置 } return 0; }
#includeregex_replace#include #include using namespace std; int main() { //匹配多个符合要求的字符串 string str = "2019-08-07,2019-08-08,2019-08-09"; smatch match; regex pattern("(\d{4})-(\d{1,2})-(\d{1,2})"); string::const_iterator citer = str.cbegin(); while (regex_search(citer, str.cend(), match, pattern))//循环匹配 { citer = match[0].second; for (size_t i = 1; i < match.size(); ++i) { cout << match[i] << " "; } cout << endl; } return 0; }
替换匹配,即可以将符合匹配规则的子字符串替换为其他字符串。
将字符串中的-替换为/#include匹配以逗号分隔的字符串(S表示匹配任意显示字符) 使用正则表达式将所有信息批处理为sql的语句 使用正则表达式1999-10-7 修改为 10/7/1999#include using namespace std; int main() { //替换不会修改原串 cout << regex_replace("2019-08-07", regex("-"), "/") << endl; return 0; }
先匹配上,再拿小括号获取值 然后替换
然后就可以放在程序中
int main()
{
string str;
cin >> str;
cout << regex_replace(str, regex("(\d{4})-(\d{1,2})-(\d{1,2})"), "$2/$3/$1");
return 0;
}
将字符串中的/删掉



