c++正则表达式用法详解

C++11正式加入了regex库,下面通过几个简单的例子介绍一下regex库的使用。

要使用regex库,要包含头文件#include <regex>
在这里插入图片描述

构造正则表达式

构造正则表达式用到一个类:basic_regex。basic_regex是一个正则表达式的通用类模板,对char和wchar_t类型都有对应的特化:

typedef basic_regex<char>    regex;
typedef basic_regex<wchar_t> wregex;

构造函数比较多,但是非常简单:

//默认构造函数,将匹配任何的字符序列
basic_regex();
//用一个以‘\0’结束的字符串s构造一个正则表达式
explicit basic_regex( const CharT* s,flag_type f =std::regex_constants::ECMAScript );
//同上,但是制定了用于构造的字符串s的长度为count
basic_regex( const CharT* s, std::size_t count,flag_type f = std::regex_constants::ECMAScript );
//拷贝构造,不赘述
basic_regex( const basic_regex& other );
 //移动构造函数
basic_regex( basic_regex&& other );
//以basic_string类型的str构造正则表达式
template< class ST, class SA >
explicit basic_regex( const std::basic_string<CharT,ST,SA>& str, flag_type f = std::regex_constants::ECMAScript );
//指定范围[first,last)内的字符串构造正则表达式
template< class ForwardIt >
basic_regex( ForwardIt first, ForwardIt last, flag_type f = std::regex_constants::ECMAScript );
//使用initializer_list构造
basic_regex( std::initializer_list<CharT> init, flag_type f = std::regex_constants::ECMAScript );

以上除默认构造之外的构造函数,都有一个flag_type类型的参数用于指定正则表达式的语法,ECMASCRIPT、basic、extended、awk、grep和egrep均是可选的值。除此之外还有其他几种可能的的标志,用于改变正则表达式匹配时的规则和行为:

在这里插入图片描述
有了构造函数之后,现在我们就可以先构造出一个提取http链接的正则表达式:

std::string pattern("http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?");    //匹配规则很简单,如果有疑惑,可以对照语法查看
std::regex r(pattern);

值得一提的是在C++中’‘这个字符需要转义,因此所有ECMASCRIPT正则表达式语法中的’'都需要写成“\”的形式。我测试的时候,这段regex如果没有加转义,在gcc中会给出警告提示,vs2013编译后后运行直接崩溃了。

regex_search()只查找到第一个匹配的子序列

根据函数的字面语义,我们可能会错误的选择regex_search()这个函数来进行匹配。其函数原型也有6个重载的版本,用法也是大同小异,函数返回值是bool值,成功返回true,失败返回false。鉴于篇幅,我们只看我们下面要使用的这个:

template< class STraits, class SAlloc,class Alloc, class CharT, class Traits >
bool regex_search( const std::basic_string<CharT,STraits,SAlloc>& s,
                   std::match_results<typename std::basic_string<CharT,STraits,SAlloc>::const_iterator, Alloc>& m,
                   const std::basic_regex<CharT, Traits>& e,
                   std::regex_constants::match_flag_type flags = std::regex_constants::match_default );

第一个参数s是std::basic_string类型的,它是我们待匹配的字符序列,参数m是一个match_results的容器用于存放匹配到的结果,参数e则是用来存放我们之前构造的正则表达式对象。flags参数值得一提,它的类型是std::regex_constants::match_flag_type,语义上匹配标志的意思。正如在构造正则表达式对象时我们可以指定选项如何处理正则表达式一样,在匹配的过程中我们依然可以指定另外的标志来控制匹配的规则。这些标志的具体含义,我从cppreference.com 引用过来,用的时候查一下就可以了:

在这里插入图片描述
根据参数类型,于是我们构造了这样的调用:

std::smatch results;<br>regex_search(html,results,r);

不过,标准库规定regex_search()在查找到第一个匹配的子串后,就会停止查找!在本程序中,results参数只带回了第一个满足条件的http链接。这显然并不能满足我们要提取网页中所有HTTP链接需要。

使用regex_iterator匹配所有子串

严格意义上regex_iterator是一种迭代器适配器,它用来绑定要匹配的字符序列和regex对象。regex_iterator的默认构造函数比较特殊,就直接构造了一个尾后迭代器。另外一个构造函数原型:

regex_iterator(BidirIt a, BidirIt b,                                                           //分别是待匹配字符序列的首迭代器和尾后迭代器
               const regex_type& re,                                                           //regex对象
               std::regex_constants::match_flag_type m = std::regex_constants::match_default); //标志,同上面的regex_search()中的

和上边的regex_search()一样,regex_iterator的构造函数中也有std::regex_constants::match_flag_type类型的参数,用法一样。其实regex_iterator的内部实现就是调用了regex_search(),这个参数是用来传递给regex_search()的。用gif或许可以演示的比较形象一点,具体是这样工作的(颜色加深部分,表示可以匹配的子序列):

在这里插入图片描述
首先在构造regex_iterator的时候,构造函数中首先就调用一次regex_search()将迭代器it指向了第一个匹配的子序列。以后的每一次迭代的过程中(++it),都会在以后剩下的子序列中继续调用regex_search(),直到迭代器走到最后。it就一直“指向”了匹配的子序列。

知道了原理,我们写起来代码就轻松多了。结合前面的部分我们,这个程序就基本写好了:

#include <iostream>
#include <regex>
#include <string>
 
int main()
{
    std::string tmp,html;
    while(getline(std::cin,tmp))
    {
        tmp += '\n';
        html += tmp;
    }
    std::string pattern("http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?");
    pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*";
    std::regex r(pattern);
    for (std::sregex_iterator it(html.begin(), html.end(), r), end;     //end是尾后迭代器,regex_iterator是regex_iterator的string类型的版本
        it != end;
        ++it)
    {
        std::cout << it->str() << std::endl;
    }
}

regex_match全文匹配

cout << regex_match("123", regex("\\d")) << endl;		//结果为0
cout << regex_match("123", regex("\\d+")) << endl;		//结果为1

上述方法返回值为bool值,主要用于if条件表达式中。

更多的时候我们希望能够获得匹配结果(字符串),对结果进行操作。这时就需要对匹配结果进行存储,共有两种存储方式。

match_results<string::const_iterator> result;
smatch result;			//推荐

第二种方式使用起来更简洁、方便,推荐使用。

下面看一个match方法匹配的实例,看看实际应用:

string str = "Hello_2018";
smatch result;
regex pattern("(.{5})_(\\d{4})");	//匹配5个任意单字符 + 下划线 + 4个数字

if (regex_match(str, result, pattern))
{
	cout << result[0] << endl;		//完整匹配结果,Hello_2018
	cout << result[1] << endl;		//第一组匹配的数据,Hello
	cout << result[2] << endl;		//第二组匹配的数据,2018
	cout<<"结果显示形式2"<<endl;
	cout<< result.str() << endl;	//完整结果,Hello_2018
	cout<< result.str(1) << endl;	//第一组匹配的数据,Hello
	cout << result.str(2) << endl;	//第二组匹配的数据,2018
}

//遍历结果
for (int i = 0; i < result.size(); ++i)
{
	cout << result[i] << endl;
}

result[]与result.str()这两种方式能够获得相同的值,我更喜欢用数组形式的。

在匹配规则中,以括号()的方式来划分组别,实例中的规则共有两个括号,所以共有两组数据。

regex_replace

replace是替换匹配,即可以将符合匹配规则的子字符串替换为其他字符串。

string str = "Hello_2018!";
regex pattern("Hello");	
cout << regex_replace(str, pattern, "") << endl;	//输出:_2018,将Hello替换为""
cout << regex_replace(str, pattern, "Hi") << endl;	//输出:Hi_2018,将Hello替换为Hi

  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值