1、匹配字符串是否包含某些字符,可以使用regex_match,但是这个是全字匹配,不能部分匹配,比如
using namespace std;
int main()
{
std::string str = "1234";
std::regex reg("\\d+");
bool ret = std::regex_match(str, reg);
if (ret)
{
std::cout << "have" << std::endl;
}
else
{
std::cout << "no" << std::endl;
}
getchar();
}
结果为have,但是你把str换成abc123就是no,因为它需要全字匹配,你可以把正则表达改成abc\\d+,如果你需要部分匹配可以使用下面例子
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main()
{
std::string str = "abc123";
std::regex reg("\\d+");
bool ret = std::regex_search(str, reg);
if (ret)
{
std::cout << "have" << std::endl;
}
else
{
std::cout << "no" << std::endl;
}
getchar();
}
2、匹配字符串里面一个子字符串。比如abc123efg456只匹配到第一个返回。
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main() {
std::regex reg("\\d+");
std::cmatch m;
auto ret = std::regex_search("abc123efg456", m, reg);
if (ret)
{
for (auto& elem : m)
std::cout << elem << std::endl;
}
std::cout << "prefix:" << m.prefix() << std::endl;
std::cout << "suffix:" << m.suffix() << std::endl;
getchar();
}
输出:
123
prefix:abc
suffix:efg456
3、正则替换
将所有的字符串数字替换成空
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main() {
std::regex reg("\\d+");
std::string str = "abc123efg456";
std::string res = std::regex_replace(str, reg,"");
std::cout << res << std::endl;
getchar();
}
输出:
abcefg
4、求出字符串所有匹配到的结果,比如提取字符串中所有数字
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main() {
std::regex reg("(\\d+)");
std::string str = "abc123efg456jkp789";
std::smatch m;
sregex_iterator pos(str.cbegin(), str.cend(), reg);
sregex_iterator end;
for (; pos != end; ++pos)
{
std::cout<<pos->str(0)<<"\n";
}
getchar();
}
输出结果:
123 456 789
5、提取正则子表达式内容
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main() {
std::regex reg("(\\d+)");
std::string str = "abc123efg456jkp789";
std::smatch m;
sregex_token_iterator pos(str.cbegin(), str.cend(), reg, 1);// 表示第一个分组,再换成0、2、-1感受一下
sregex_token_iterator end;
for (; pos != end; ++pos)
{
std::cout<<pos->str()<<"\n";
}
getchar();
}
输出结果:
123 456 789