Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex ungreedy from the left side (i.e., narrowest match possible from both sides)

Let's say I'm trying to match /dog.*lab/ against this text:

"I have a dog. My dog is a black lab. He was created in a laboratory."

Greedily, it would match "dog. My dog is a black lab. He was created in a lab".

I want to find the matches that are narrowest from both sides. If I use the ungreedy modifier like
/dog.*?lab/ or /dog.*lab/U it will match less but still too much:
"dog. My dog is a black lab"

Is there a way to make my search ungreedy from the left also, thus matching only "dog is a black lab"?

Much thanks. Sorry for the contrived example.

like image 241
Wiseguy Avatar asked Aug 23 '10 16:08

Wiseguy


1 Answers

You could use a look-ahead assertion that excludes the occurrence of dog between dog and lab:

/dog(?:(?!dog).)*?lab/
like image 114
Gumbo Avatar answered Sep 26 '22 14:09

Gumbo