首页 > 技术文章 > C++ 正则表达式 零宽断言 lookbehind

tengzijian 2021-09-05 16:29 原文

正则表达式零宽断言

适用场景:匹配/提取/查找/替换以 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 时指定可选标志,使用其他正则表达式语法 ==> 验证失败

推荐阅读