正则表达式是解决大量模式匹配问题的基础。它们常用于处理大的字符串,子串模糊查找,按某种格式tokenize字符串,或者是基于某种规则修改字符串。
1、元字符
. 匹配除换行符以外的任意字符
\w 匹配字母或数字或下划线或汉字
\s 匹配任意的空白符
\d 匹配数字
\b 匹配单词的开始或结束
^ 匹配字符串的开始
$ 匹配字符串的结束
2、转义
\ 后接特殊字符
3、重复
*
重复零次或多次
+
重复1次或多次
?重复0次或一次
{n}重复n次
{n,} 重复n次或更多次
{n,m} 重复n到m次
4、字符类
[aeiou] 匹配元音字符
[a-z0-9] 支持匹配一个范围
5、分枝条件
| 匹配两个正则表达式的其中之一
6、分组
()在后面接重复数字可以重复里面的表达式
7、反义
\W 匹配任意不是字母,数字,下划线,汉字的字符
\S 匹配任意不是空白符的字符
\D 匹配任意非数字的字符
\B 匹配不是单词开头或结束的位置
[^x] 匹配除x以外的任意字符
8、后向引用
#include <string>
#include <boost/regex.hpp>
bool validate_card_format(const std::string& s)
{
static const boost::regex e("(\\d{4}[- ]){3}\\d{4}");
return boost::regex_match(s, e);
}
const boost::regex e("\\A(\\d{3,4})[- ]?(\\d{4})[- ]?(\\d{4})[- ]?(\\d{4})\\z");
const std::string machine_format("\\1\\2\\3\\4");
const std::string human_format("\\1-\\2-\\3-\\4");
std::string machine_readable_card_number(const std::string& s)
{
return boost::regex_replace(s, e, machine_format, boost::match_default | boost::format_sed);
}
std::string human_readable_card_number(const std::string& s)
{
return boost::regex_replace(s, e, human_format, boost::match_default | boost::format_sed);
}
#include <iostream>
using namespace std;
int main()
{
string s[4] = { "0000111122223333", "0000 1111 2222 3333",
"0000-1111-2222-3333", "000-1111-2222-3333", };
int i;
for(i = 0; i < 4; ++i)
{
cout << "validate_card_format(\"" << s[i] << "\") returned " << validate_card_format(s[i]) << endl;
}
for(i = 0; i < 4; ++i)
{
cout << "machine_readable_card_number(\"" << s[i] << "\") returned " << machine_readable_card_number(s[i]) << endl;
}
for(i = 0; i < 4; ++i)
{
cout << "human_readable_card_number(\"" << s[i] << "\") returned " << human_readable_card_number(s[i]) << endl;
}
return 0;
}
注:编译命令g++ main.cpp -o main -lboost_regex -lboost_iostreams
参考:https://imlonghao.com/49.html