您的位置:首页 > 编程语言 > C语言/C++

C++ 正则表达式 零宽断言 lookbehind

2021-09-05 16:29 549 查看

正则表达式零宽断言

适用场景:匹配/提取/查找/替换以 xxx 开头,或以 xxx 结尾,但不包括 xxx 的字符串。

零宽断言 用法 含义
(?=exp)
零宽度正预测先行断言 lookahead
exp1(?=exp2)
exp1
之后必须匹配
exp2
,但匹配结果不含
exp2
(?!exp)
零宽度负预测先行断言 lookahead
exp1(?!exp2)
exp1
之后必须不匹配
exp2
(?<=exp)
零宽度正回顾后发断言 lookbehind
(?<=exp0)exp1
exp1
之前必须匹配
exp0
,但匹配结果不含
exp0
(?<!exp)
零宽度负回顾后发断言 lookbehind
(?<!exp0)exp1
exp1
之前必须不匹配
exp0

示例:提取

【123】
中的
123
的正则表达式:
(?<=【)\d+(?=】)

问题描述

正则表达式匹配形似

qq=123456
的字符串,从中提取
123456
,但不包括
qq=
。首先想到的是直接利用零宽断言 lookbehind 去匹配,正则表达式很容易写出来
(?<=qq=)[0-9]+
,但是在 C++ 运行阶段报错:

terminate called after throwing an instance of 'std::regex_error'
what():  Invalid special open parenthesis.
Aborted (core dumped)

问题分析

目前 C++ 标准库正则表达式不支持零宽后行断言(也叫零宽度正回顾后发断言,lookbehind),即

(?<=exp)
(?<!exp)
语法。但支持零宽前行断言(lookahead)。

Finally, flavors like std::regex and Tcl do not support lookbehind at all, even though they do support lookahead. JavaScript was like that for the longest time since its inception. But now lookbehind is part of the ECMAScript 2018 specification. As of this writing (late 2019), Google’s Chrome browser is the only popular JavaScript implementation that supports lookbehind. So if cross-browser compatibility matters, you can’t use lookbehind in JavaScript.

解决方案

  1. 构造 regex 时指定可选标志,使用其他正则表达式语法 ==> 验证失败 😦
  2. 把待提取部分用()括起来,作为一个独立子表达式 ==> 验证可行 😃
  3. 使用支持 lookbehind 的 Boost 正则 ==> 未验证

示例代码

#include <iostream>
#include <regex>
#include <string>

using namespace std;
using namespace regex_constants;

int main()
{
string seq = "[optional]qq=123456;";
string pattern_nok = "(?<=qq=)[0-9]+"; // C++ 正则表达式不支持 lookbehind,运行时报错
string pattern = "qq=([0-9]+)"; // 将数字部分单独作为一个子表达式
regex r(pattern /*, extended*/); // 可以在这里修改默认正则表达式语法,然而并没有什么用
smatch results;

if (regex_search(seq, results, r))
{
cout << results[0] << endl; // 打印整个匹配
cout << results[1] << endl; // 打印第一个正则子表达式
}
}

输出结果

qq=123456
123456

Reference

https://c.runoob.com/front-end/854/ http://c.biancheng.net/cpp/html/1414.html https://www.zhihu.com/question/391339488 https://bbs.csdn.net/topics/397367228?list=78619228 https://www.geek-share.com/detail/2725098759.html https://www.cnblogs.com/ProjectDD/p/10634300.html https://www.jianshu.com/p/b5194398efb2 https://cuiqingcai.com/5788.html

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: