Matching first instance of p tag with RegExp

I’ve been beating my head against the wall to get this pattern right, but anything I do, I end up selecting my whole string. What I want to do is to select the first instance of a p tag, that wraps an img tag, and its closing tag. Here’s a dummy example:

<p><img src="http://www.churchplanting.com/wp-content/uploads/2012/02/dummy.jpg" alt="image"></p><p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...</p><p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."</p><p><img src="https://upload.wikimedia.org/wikipedia/commons/4/49/Testing22222.jpg" alt="image"></p>

Here are the facts:
-The string is minified and adding line breaks isn’t an option for my case
-I’m updating a database so I can’t use that link in the pattern
-The p tag will always start the strings
-Here’s what I got so far:

^<p><img src="https?:\/\/\S.+

I imagine that’s a good start already, but I haven’t found anything to stop matching after the first </p>. Anyone have a tip I can use?

Edit: Here’s the same string using text-wrap for better visibility:

<p><img src="http://www.churchplanting.com/wp-content/uploads/2012/02/dummy.jpg" alt="image"></p>
<p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...</p>
<p>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/4/49/Testing22222.jpg" alt="image"></p>

The following should stop at the close of the paragraph

^<p><img src="https?:\/\/\S.+?<\/p>
1 Like

Jackpot! I’ve seen a few examples that had the question mark, but still I don’t know what it’s doing. Would you mind explaining that, @felgall?

Edit: I found that the question mark makes the preceding quantifier lazy, causing it to match as few characters as possible. By default, quantifiers are greedy, and will match as many characters as possible.

Therefore, it will stop matching as soon as it finds the first instance of </p>, is that correct?

Yes, as shown at

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.