jayyys
jayyys

Reputation: 11

Perl Regex Substitute paragraph tag

I am trying to use a regex to replace contents inside of paragragh tags with contents followed by br br tags

 s/^[<]p[>](.+)[<][/]p[>]/\1[<]br[>][<]br[>]/

I am getting error Unmatched [ in regex marked by <---HERE m/^[<]p>[<][

I tried changing [/] to backslash/ but im not really sure how to go about this. Thank you =]

I actually got it was

s/^<p>(.+)<\/p>/\1<br><br>/;

Upvotes: 1

Views: 247

Answers (2)

kshenoy
kshenoy

Reputation: 1826

Try this:

s#(?=</p>)#<br><br>#

Whenever dealing with a /, I like to use another separator. Here I'm using #.

Since, you just want to append <br><br> and not touch anything else in <p>..</p>, we can use a lookahead anchor. That is what (?=...) does. It looks for a point after which there is a </p> and substitutes it with the replacement string.

Note that look-around expressions are zero-width i.e. they do not match any char.

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627066

You can use this version of your regex:

s/<p>(.+?)<\/p>/\1<br><br>/si

I removed string start anchor ^, it is highly possible you do not need it. .+? will make sure you will match the closest matching </p>. The si options will enable case-insensitive matching, and . will also match newline symbols.

Upvotes: 0

Related Questions