目录
正则表达式相关概念
正则表达式(规则表达式)通常被用来检索、替换那些符合某个模式(规则)的文本。
是由普通字符集特殊字符(元字符)组成的字符模式。其作为一个模板,将某个字符模式与所搜索的字符串进行匹配。
正则表达式相关含义
(1) 需加头文件
#include <regex>
(2) 字符规则
字符 | 描述 |
\ | 转义字符 |
^ | 匹配字符行首 |
$ | 匹配字符行尾 |
* | 匹配前面的子表达式任意多次 |
+ | 匹配前面的子表达式一次或多次 |
? | 匹配前面的子表达式0次或一次 |
{m} | 匹配确定的m次 |
{m,} | 匹配至少m次 |
{m,n} | 最少匹配m次,最大匹配n次 |
. | 匹配任意字符 |
x|y | 匹配x或y |
[xyz] | 字符集合,匹配包含的任意一个字符 |
[^xyz] | 匹配未包含的任意字符 |
[a-z] | 字符范围,匹配指定范围内的任意字符 |
[^a-z] | 匹配任何不在指定范围内的任意字符 |
regex_match
全文匹配,即要求整个字符串符合匹配规则,返回true或false。
(1) 匹配手机号
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main()
{
string number;
while (true)
{
cout << "输入手机号:";
cin >> number;
// if (regex_match(number, regex("133[0-9]{8}"))) {
if (regex_match(number, regex("133\\d{8}"))) {
cout << "ok" << endl;
break;
}
else {
cout << "no" << endl;
}
}
return 0;
}
(2) 匹配邮箱号
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main()
{
string data;
while (true)
{
cout << "输入邮箱号:" << endl;
cin >> data;
//qq不支持数字加字母格式,这里表示统一示范格式
// if (regex_match(data, regex("\\w+@(qq|163|126)\\.com"))) {
// if (regex_match(data, regex("[a-zA-Z0-9_\u4e00-\u9fa5]+@(qq|163|126)\\.com"))) {
if (regex_match(data, regex("[a-zA-Z0-9_]+@(qq|163|126)\\.com"))) {
cout << "ok" << endl;
break;
}
else
{
cout << "no" << endl;
}
}
return 0;
}
regex_search
搜索匹配,即搜索字符串中存在符合规则的子字符串。
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main()
{
//匹配单个
string str = "hello2024-04-15word";
smatch match;//搜索结果
regex pattern("(\\d{4})-(\\d{1,2})-(\\d{1,2})");//搜索规则 ()表示把内容拿出来
if (regex_search(str, match, pattern))
{
cout<<match[i]<<endl;
}
//匹配多个
string str = "2024-04-14,2024-04-15,2024-04-16";
smatch match;
regex pattern("(\\d{4}-\\d{1,2}-\\d{1,2})");
string::const_iterator iter = str.cbegin();
while (regex_search(iter,str.cend(),match,pattern))
{
iter = match[0].second;//表示开始和结束位置
for (size_t i=1;i<match.size();++i)
{
cout << match[i] << endl;
}
}
return 0;
}
regex_replace
替换匹配,即可以将符合匹配规则的子字符串替换为其他字符串。
//将字符串中的-替换为/
cout << regex_replace("2019-08-07", regex("-"), "/") << endl;
//将字符串中2019替换为2024
cout << regex_replace("2019-08-07", regex("2019"), "2024") << endl;