php preg_match 非贪婪?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/14967485/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php preg_match non greedy?
提问by Chris Muench
I have a string (from a file):
我有一个字符串(来自文件):
ILX (New for 2013!)
Overview: The least expensive route to Honda's premium-label goodness
Drivetrain: Two four-cylinder engines to choose from as well as a gas-electric hybrid; front-wheel-drive only.
How I get the string:
我如何获得字符串:
$writeup = file_get_contents($car_files_path . $manufacture . '/Stories/'.$story);
I want to match the overview line (Overview: The least expensive route to Honda's premium-label goodness). What is the best way to achieve this.
我想匹配概览行 ( Overview: The least expensive route to Honda's premium-label goodness)。实现这一目标的最佳方法是什么。
I tried .*\n, but that will match everything and then a new line. Is there a way to make regex non-greedy?
我试过 .*\n,但这将匹配所有内容,然后是一个新行。有没有办法让正则表达式不贪婪?
I have tried:
preg_match('/^Overview:\s.*$/im', $writeup, $overall_matches)and I don't get any matches
我试过了:但
preg_match('/^Overview:\s.*$/im', $writeup, $overall_matches)我没有得到任何匹配
回答by Niet the Dark Absol
Add ?after the quantifier to make it ungreedy. In this case, your regex would be .*?\n.
?在量词之后添加以使其不贪婪。在这种情况下,您的正则表达式将是.*?\n.
To specifically match the line beginning with "Overview: ", use this regex:
要专门匹配以“概述:”开头的行,请使用以下正则表达式:
/^Overview:\s.*$/im
The mmodifier allows ^and $to match the start and end of lines instead of the entire search string. Note that there is no need to make it ungreedy since .does not match newlines unless you use the smodifier - in fact, making it ungreedy here would be bad for performance.
该m修改允许^和$匹配线,而不是整个搜索字符串的开始和结束。请注意,.除非您使用s修饰符,否则不需要使其不匹配换行符,因为不匹配换行符- 事实上,在此处使其不贪婪对性能不利。

