Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a newline \n in a perl regex?

Tags:

regex

perl

I want to match this line,

<center>'''<font color="blue"><font size="18.0pt">No Change Alarms Help &amp; Information</font></font>'''</center>

and replace it with,

=<center>'''<font color="blue">No Change Alarms Help &amp; Information</font>'''</center>=

Now it would be simple if the tags were always font colour or center, but they can be absolutely anything and there can be multiple of them.

My current code is this:

$html =~ s/<font size=".+">(.+)<\/font>/$1/g;

but this obviously does not do the = on each end.

What I would like to do is this:

$html =~ s/\n(.+)<font size=".+">(.+)<\/font>(.+)\n/=$1$2$3=/g;

However it fails to match the newline characters and I cannot figure out how to make it match them, any clues?

(I'm converting html to wiki markup, however the converter stuffs up the font sizes so I'm manually converting them to wiki style headings.)

like image 293
rollsch Avatar asked Dec 21 '10 02:12

rollsch


People also ask

How do I match a new line in a regular expression in Perl?

i think this will work,using the /s modifier, which mnemonically means to "treat string as a single line". This changes the behaviour of "." to match newline characters as well. In order to match the beginning of this comment to the end, we add the /s modifier like this: $str =~ s/<!

How do you match a new line in regex?

"\n" matches a newline character.

Does match newline regex?

By default in most regex engines, . doesn't match newline characters, so the matching stops at the end of each logical line. If you want . to match really everything, including newlines, you need to enable "dot-matches-all" mode in your regex engine of choice (for example, add re. DOTALL flag in Python, or /s in PCRE.

Does \s match newline?

According to regex101.com \s : Matches any space, tab or newline character.


2 Answers

All I needed was /gm on the end of my query, turns out it ignores new lines by default.

like image 83
rollsch Avatar answered Oct 14 '22 04:10

rollsch


In some cases it might not work because of how perl "slurps" the input. Passing -0777 as a parameter will make it consider multiple lines. (Pass it along with your other parameters, e.g. perl -0777pi -e)

like image 32
Nikolay Suvandzhiev Avatar answered Oct 14 '22 06:10

Nikolay Suvandzhiev