PCRE正则表达式重叠匹配 [英] PCRE regular expression overlapping matches

查看:118
本文介绍了PCRE正则表达式重叠匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串

001110000100001100001

和该表达式

/[1]....[1]/g

这将进行两次匹配

但是我希望它也可以使两者之间的模式相匹配,也就是说,重叠的1

but i want it to also match the pattern between those both with lookbehind so to say, the overlapping 1

我完全不知道,这怎么工作?而不是0,它可以是任何字符

i have absolutely no clue, how can this work ? instead of 0 it can be any characters

推荐答案

一个常见的技巧是在未锚定的积极前瞻中使用捕获技术.将此正则表达式与preg_match_all一起使用:

A common trick is to use capturing technique inside an unanchored positive lookahead. Use this regex with preg_match_all:

(?=(1....1))

请参见 regex演示

值在$matches[1] 中:

$re = "/(?=(1....1))/"; 
$str = "001110000100001100001"; 
preg_match_all($re, $str, $matches);
print_r($matches[1]);

请参见提前引用:

环顾四周实际上是匹配字符,但随后放弃匹配,仅返回结果:匹配或不匹配.这就是为什么它们被称为断言"的原因.它们不使用字符串中的字符,而仅声明是否可以进行匹配.

Lookaround actually matches characters, but then gives up the match, returning only the result: match or no match. That is why they are called "assertions". They do not consume characters in the string, but only assert whether a match is possible or not.

如果要在正则表达式中存储正则表达式的匹配项,则必须在正则表达式内将正则表达式周围的括号括起来,如下所示:(?=(regex)) .

If you want to store the match of the regex inside a lookahead, you have to put capturing parentheses around the regex inside the lookahead, like this: (?=(regex)).

这篇关于PCRE正则表达式重叠匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆