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="(.*)".*/

Does not seem to work.


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.


location="(.*)"将从“after location= ”之后匹配到“after some="xxx除非让它变得非贪婪,所以你需要.*? (即使它不贪婪)或者更好地替换.*[^"]*


How about

.*location="([^"]*)".*

This avoids the unlimited search with .* and will match exactly to the first quote.

链接地址: http://www.djcxy.com/p/13444.html

上一篇: 正则表达式只能匹配两个单词

下一篇: 正则表达式在第一场比赛中停止