如何编写与非贪婪匹配的正则表达式? [英] How can I write a regex which matches non greedy?

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

问题描述

我需要有关非贪婪选项的正则表达式匹配的帮助.

I need help about regular expression matching with non-greedy option.

匹配模式为:

<img\s.*>

要匹配的文本是:

<html>
<img src="test">
abc
<img
  src="a" src='a' a=b>
</html>

我在 http://regexpal.com

此表达式匹配从<img到最后一个>的所有文本.我需要它与初始<img之后的第一个遇到的>匹配,所以在这里,我需要得到两个匹配项,而不是我得到的匹配项.

This expression matches all text from <img to last >. I need it to match with the first encountered > after the initial <img, so here I'd need to get two matches instead of the one that I get.

我尝试了非贪婪? 的所有组合,但均未成功.

I tried all combinations of non-greedy ?, with no success.

推荐答案

非贪婪的?效果很好.只需在要测试的正则表达式引擎中选择全部匹配选项(您使用的引擎 regexpal 也具有此选项).这是因为,使用.时,正则表达式引擎通常不匹配换行符.您需要明确告诉他们您也想使用.

The non-greedy ? works perfectly fine. It's just that you need to select dot matches all option in the regex engines (regexpal, the engine you used, also has this option) you are testing with. This is because, regex engines generally don't match line breaks when you use .. You need to tell them explicitly that you want to match line-breaks too with .

例如,

<img\s.*?>

工作正常!

在此处查看结果.

此外,请阅读 的行为正则表达式.

Also, read about how dot behaves in various regex flavours.

这篇关于如何编写与非贪婪匹配的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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