正则表达式描述了一种字符串匹配的模式,检查另一个字符串是否有其子串。可以用于字串匹配,提取和替换
正则表达式有两种引擎:DFA 自动机(Deterministic Final Automata 确定型有穷自动机)和 NFA 自动机(Non deterministic Finite Automaton 不确定型有穷自动机)
DFA自动机的时间复杂度是线性稳定的,但是功能是有限的
NFA自动机的时间复杂度是不稳定的,但是功能比较多,现代编程语言绝大多数是用它去实现的正则表达式
C++11的新特性之一就是正则表达式,下面主要讲C++下的正则表达式的使用:
正则表达式的匹配:
#include<iostream>
#include<regex>
using namespace std;
int main()
{
string str = "hhh233";
regex r("[a-z0-9]+");
bool flag = regex_match(str,r);
}
有一个坑,尤其要注意C++里面本身的/作为转义字符,当要匹配一个“\”时候得这么写
#include<iostream>
#include<regex>
using namespace std;
int main()
{
string s1="\\";
regex ex("\\\\");
bool a=regex_match(s1,ex);
cout<<a<<endl;
}
正则表达式的提取:
提取单个:
#include<iostream>
#include<regex>
using namespace std;
int main()
{
string s = "ab1def";
regex ex("[a-z]+");
smatch match;
regex_search(s, match, ex);
cout << s << " contains digit: " << match[0] << endl;
}
提取多个:
#include<iostream>
#include<regex>
using namespace std;
int main()
{
string str="123<xml>value</xml>456";
regex ex("<(.*)>(.*)</\\1>"); //\1为第一回匹配的.
smatch match;
auto ret = regex_search(str, match, ex);
for (auto& elem : match)
{
std::cout << elem << std::endl;
}
}
正则表达式的替换:
#include<iostream>
#include<regex>
using namespace std;
int main()
{
string s = "ab123cdef";
regex ex("[a-z]+");
string r = regex_replace(s, ex, "A");
cout << r << endl;
}
这里只介绍C++调用正则的方式,具体正则表达式语法以后更新
后续:文章已经发表: