正则表达式在字符匹配上有很巧妙的作用,特别是字符串形式或者结构的检查方面。C语言没有源生的正则表达式库函数或者头文件,而C++和Python具有。
- C++
C++的正则表达书头文件是,这是regular expression正则表达式的缩写。具体的应用实例:
例1:
#include <iostream>
#include <regex>
using namespace std;
int main(){
string str="abce1";
regex r("[a-z]+");
cout<<regex_match(str,r)<<endl;;
return 0;
}
例2:
#include <iostream>
#include <regex>
using namespace std;
int main(){
string str1="abce";
string str2="abc123@123.xyz";
regex r1("[a-z]+");
regex r2("[a-z0-9]+@[a-z0-9]+\\.[a-z0-9]+");
cout<<regex_match(str1,r1)<<" "<<regex_match(str2,r2)<<endl;;
return 0;
}
//output:
// 1 1
- Python
Python的正则表达式和C++非常相似。使用前需要先导入re库