tags:

views:

69

answers:

3

My 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? Does not seem to work :(

/.*location="(.*)".*/
+2  A: 

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.

Daniel Vandersluis
+1  A: 

Use non-greedy matching, if your engine supports it. Add the ? inside the capture.

/location="(.*?)"/
mrjoltcola
+4  A: 

location="(.*)" will match from the " after location= until the " after some="xxx unless you make it non-greedy. So you either need .*? (i.e. make it non-greedy) or better replace .* with [^"]*.

sepp2k
+1, `[^"]*"` is clearer than `.*?"` any day
Kip