[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

相关推荐
AOwhisky16 分钟前
Python 学习笔记(第五期)——组合数据类型:列表、元组、集合与字典精讲——核心知识点自测与详解
开发语言·笔记·python·学习·云计算
小保CPP18 分钟前
OpenCV C++提取webp动图里的图片
c++·人工智能·opencv·计算机视觉
炸膛坦客9 小时前
单片机/C/C++八股:(二十六)IIC 专题(I²C)---- 上集
c语言·c++·单片机
旖-旎9 小时前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
灯澜忆梦9 小时前
GO_并发编程---定时器
开发语言·后端·golang
-银雾鸢尾-10 小时前
C#中的StringBuilder相关方法
开发语言·c#
Henry Zhu12310 小时前
C++中的特殊成员函数与智能指针
c++
-银雾鸢尾-10 小时前
C#中结构体与类的区别;抽象类与接口的区别
开发语言·c#
大模型码小白11 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
_wyt00112 小时前
多重背包问题详解
c++·背包dp