Home > Enterprise >  How to select exact string with multiple words and chars with regex?
How to select exact string with multiple words and chars with regex?

Time:04-12

I have a code like this:

<p>test1</p> 
<p>Word1 word2 word3 <a href="https://example.com/q1/asdq/">word4 word5 word6</p><div style="padding:123</div> 
<p>test2</p>

I need to select only middle paragraph with regex. Tried something like this:

^(<p>Word1).*(<\/div>)$

but it didn't work. What expression do I need to use?

CodePudding user response:

The following pattern looks for "Word1" just after a <p> tag and takes everything before the next closing </p> tag.

<p>(Word1((?!<\/p>).)*)

see https://regex101.com/r/OTuCo0/2 The value in the capturing group is therefore

Word1 word2 word3 <a href="https://example.com/q1/asdq/">word4 word5 word6

which can be used with either $1 or \1 in most flavours of regex.

  • Related