又称为: 规则表达式。
作用: 一般用于 检索 或者替换某些符合所选设置规则(或模式)的文本
使用: 正则表达式是 普通字符或者一些特殊字符组成的字符模式,将此作为一个字符模板进行与所需要的文本进行字符串的模糊匹配,以达到所需要的效果
正则表达式常用字符:
头文件: #include
三种用法:
regex_match :全文匹配,即要求整个字符串符合匹配规则,返回true或false(不改变字符串本身)
regex_search:搜索匹配,即搜索字符串中存在符合规则的子字符串。
regex_replace: 替换匹配,即可以将符合匹配规则的子字符串替换为其他字符串。(会改变字符串本身)
测试代码:
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include#include #include using namespace std; int main1() { string n; int res = 0; while (!res) { cout << "请输入手机号" << endl; cin >> n; res = regex_match(n, regex("132\d{8}")); cout << res << endl; if (res == 0) { cout << "输入格式不正确" << endl; } } return 0; } //判断邮箱地址为 数字或者字母或者数字加字母(至少两位)@ 数字或者字母或者数字加字母(至少两位).com 为正确格式 int main2() { string n; int res = 0; while (!res) { cout << "请输入邮箱地址" << endl; cin >> n; res = regex_match(n, regex("[a-z,0-9,A-Z]{2,}@[A-Z|a-z|0-9]{2,}\.com")); cout << res << endl; if (res == 0) { cout << "输入格式不正确" << endl; } else { cout << n << endl; } } return 0; } //判断输入的是否为数字 int main3() { string n; int res = 0; while (!res) { cout << "请输入数字" << endl; cin >> n; // res = regex_match(n, regex("[0-9]{1,}\.{0,1}[0-9]{0,}")); res = regex_match(n, regex("0|[1-9]+[0-9]{1,}|0\.+\d{1,}|[1-9]{1,}\d{0,}\.+\d{1,}")); if (res == 0) { cout << "输入格式不正确" << endl; } else { cout << n << endl; } } return 0; } //抽取字符串中的指定元素 int main4() { string str = "hello2012-12-12world!!!!!"; smatch match; regex pattern("(\d{4})-(\d{1,2})-(\d{1,2})"); if (regex_search(str,match,pattern)) { for (size_t i = 1; i < match.size(); ++i) { cout << match[i] << endl; } } return 0; } int main() { string str = "2019-08-07,2019-08-08,2019-08-09,2019-12-22"; smatch match; regex pattern("(\d{4}-\d{1,2}-\d{1,2})"); string::const_iterator itor = str.begin(); while (regex_search(itor,str.cend(),match,pattern)) { itor = match[0].second; for (size_t i = 1; i < match.size(); ++i) { cout << match[i] << endl; } } return 0; } int main6() { string str = "2019-08-07"; cout << regex_replace(str, regex("-"), "/") << endl; cout << str << endl; return 0; } //可以在notepad++ 尝试用正则表达式进行验证 $符号 int main7() { string str = "小明;男;22"; // smatch match; // regex pattern ("(.*);(.*);(\d+)"); // if (regex_search(str, match, pattern)) // { // for (size_t i = 1; i < match.size(); ++i) // { // cout << match[i] << endl; // } // } // else // { // cout << "查找失败" << endl; // } cout << regex_replace(str, regex("(.*);(.*);(\d+)"), "$1-$3-$2") << endl; return 0; }



