正则表达式在第一次匹配时停止 [英] Regular expression to stop at first match
本文介绍了正则表达式在第一次匹配时停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的正则表达式看起来像
My regex pattern looks something like
<xxxx location="file path/level1/level2" xxxx some="xxx">
我只对分配给位置的引号中的部分感兴趣.如果没有贪心开关,它不应该像下面一样简单吗?
I am only interested in the part in quotes assigned to location. Shouldn't it be as easy as below without the greedy switch?
/.*location="(.*)".*/
似乎不起作用.
推荐答案
你需要让你的正则表达式非贪婪,因为默认情况下,"(.*)"
会匹配所有 <代码>文件路径/level1/level2"xxx some="xxx".
You need to make your regular expression non-greedy, because by default, "(.*)"
will match all of "file path/level1/level2" xxx some="xxx"
.
相反,您可以使您的点星不贪婪,这将使其匹配尽可能少的字符:
Instead you can make your dot-star non-greedy, which will make it match as few characters as possible:
/location="(.*?)"/
在量词(?
、*
或 +
)上添加 ?
使其非贪婪.
Adding a ?
on a quantifier (?
, *
or +
) makes it non-greedy.
这篇关于正则表达式在第一次匹配时停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文