正则表达式中的前瞻总是不会捕获还是依赖? [英] Will a lookahead in regular expressions always not capture or does it depend?

查看:32
本文介绍了正则表达式中的前瞻总是不会捕获还是依赖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读本网站和网络上关于非捕获组的一些文章(例如 http://www.regular-expressions.info/brackets.htmlhttp://www.asiteaboutnothing.net/regexp/regex-disambiguation.html, ?:^"正则表达式是什么意思?, 什么是非捕获组?问号后跟冒号 (?:) 是什么意思?)

I've been reading some articles on non-capturing groups on this site and on the net (such as http://www.regular-expressions.info/brackets.html and http://www.asiteaboutnothing.net/regexp/regex-disambiguation.html, What does the "?:^" regular expression mean?, What is a non-capturing group? What does a question mark followed by a colon (?:) mean?)

我很清楚 (?:foo) 的含义.我不清楚的是 (?=foo).(?=foo) 也总是一个非捕获组,还是取决于?

I am clear on the meaning of (?:foo). What I am unclear about is (?=foo). Is (?=foo) also always a non-capturing group, or does it depend?

推荐答案

否,(?=foo) 不会捕获 "foo".任何环视断言(消极和积极向前和向后)都不会捕获,而只会检查文本的存在(或不存在).

No, (?=foo) will not capture "foo". Any look-around assertion (negative- and positive look ahead & behind) will not capture, but only check the presence (or absence) of text.

例如,正则表达式:

(X(?=\d+))

仅在后面有一位或多位数字时才匹配 "X".但是,这些数字不是比赛组 1 的一部分.

matches "X" only when there's one or more digits after it. However, these digits are not a part of match group 1.

可以定义捕获inside向前看以捕获它.例如,正则表达式:

You can define captures inside the look ahead to capture it. For example, the regex:

(X(?=(\d+)))

仅在后面有一位或多位数字时才匹配 "X".这些数字是在比赛组 2 中捕获的.

matches "X" only when there's one or more digits after it. And these digits are captured in match group 2.

一个 PHP 演示:

<?php
$s = 'X123';
preg_match_all('/(X(?=(\d+)))/', $s, $matches);
print_r($matches);
?>

将打印:

Array
(
    [0] => Array
        (
            [0] => X
        )

    [1] => Array
        (
            [0] => X
        )

    [2] => Array
        (
            [0] => 123
        )

)

这篇关于正则表达式中的前瞻总是不会捕获还是依赖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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