在正则表达式中,当您向.+添加问号时会发生什么变化 [英] In a regex, what changes when you add a question mark to .+

查看:78
本文介绍了在正则表达式中,当您向.+添加问号时会发生什么变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览旧的php源,发现了一个我不理解的模式(可能是一段时间前从互联网上复制/粘贴的...).

I was browsing old php sources and I found a pattern I don't understand (probably a copy/past from the internet some times ago ...).

这是一个与php一起使用的简单示例:

Here is a simple exemple using it with php :

echo preg_replace('#color="(.+)"#', '$1', 'color="red" color="black"');
// Echo 'red" color="black', which is fine because the (.+) try to match the largest possible string.

echo preg_replace('#color="(.+?)"#', '$1', 'color="red" color="black"');
// Echo 'red black', why ? There is some black magic behind '(.+?)' I don't understand !

那么'是什么?在'(.+?)'中做吗? 我认为它说的是与正则表达式的其余部分不匹配"之类的内容,但我正在寻找详细的解释!

So what does the '?' do in '(.+?)' ? I assume it says something like 'don't match the rest of the regex' but I'm looking for a detailed explanation !

推荐答案

+ 贪婪 运算符;尽可能多地消耗.因此,.+将尽可能匹配,并且仍然允许正则表达式的其余部分匹配.一旦指定了问号+?,您就会告诉正则表达式引擎(不要贪婪..一旦找到双引号" ...停止,您就可以完成.)

+ is a greedy operator; consuming as much as possible. Therefore, .+ will match as much as it can and still allow the remainder of the regular expression to match. Once you specify the question mark +?, you're telling the regex engine (don't be greedy.. as soon as you find a double quote "... stop, you're done.)

这篇关于在正则表达式中,当您向.+添加问号时会发生什么变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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