[C++][正则表达式]常用C++正则表达式用法

匹配字符串是否包含某些字符,可以使用regex_match,但是这个是全字匹配,不能部分匹配,比如

代码语言:javascript

AI代码解释

复制代码
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+,如果你需要部分匹配可以使用下面例子

代码语言:javascript

AI代码解释

复制代码
#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只匹配到第一个返回。

代码语言:javascript

AI代码解释

复制代码
#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();
}

输出:

代码语言:javascript

AI代码解释

复制代码
123
prefix:abc
suffix:efg456

3、正则替换

将所有的字符串数字替换成空

代码语言:javascript

AI代码解释

复制代码
#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、求出字符串所有匹配到的结果,比如提取字符串中所有数字

代码语言:javascript

AI代码解释

复制代码
#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

相关推荐
用户805533698031 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
BadBadBad__AK2 天前
线段树维护区间 k 次方和
c++·数学·算法·stl
卷无止境2 天前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境2 天前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴3 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境5 天前
C++ 的Eigen 库全解析
c++
卷无止境5 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴5 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
博客18007 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴7 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake