Regular expression to get the third part of a paragraph in HTML

Asked

Viewed 37 times

0

I created this regex and apparently it’s almost the way I’d like, however, I’d like to insert the tag <img> after the third occurrence of a sequence of paragraphs. As I did is inserting the <img> after the first paragraph of all occurrences.

That is, every third occurrence of a paragraph <p>, i would like to insert a tag <img>.

(<p(.*?)>)([[:space:]]+?|.*?|[[:space:]]+?)(<\/p>)

Here’s the example I made: https://regex101.com/r/8Dl1tr/1

Example of how my regex turned out:

Data entry:

<p>texto1</p>
<p>texto1</p>
<p>texto1</p>

Upshot:

<p>texto1</p>
   <img src="">
<p>texto1</p>
   <img src="">
<p>texto1</p>
   <img src="">

Here’s how I’d like it:

<p>texto1</p>
<p>texto1</p>
<p>texto1</p>
   <img src="">

<p>texto1</p>
<p>texto1</p>
<p>texto1</p>
   <img src="">

1 answer

0


Taking from the base what you had already done, I formulated this regex:

((<p(.*?)>)([[:space:]]+?|.*?|[[:space:]]+?)(<\/p>)\s?){3}

The only changes I made was to add everything in a single group and wait for 3 occurrences({3}).

See working on Regex101

Browser other questions tagged

You are not signed in. Login or sign up in order to post.