Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

regex - HTML content regular expression - perl

I have html content which look like this:

html code ... </div>content1</div> html code ... 
html code ... </div>content2</div> html code ...

and I would like to extract the content1/2/3... from the HTML as content1 new line content2 new line content3 any idea ? Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's an example using Mojo::DOM, inspired by this StackOverflow answer:

#!/usr/bin/env perl

use strict ;
use warnings ;

use Mojo::DOM ;

my $html = <<EOHTML;
<!DOCTYPE html>
<html>
<head>
<title>Sample HTML with 2 divs</title>
</head>
<body>
     <div>
        Four score and seven years ago our fathers brought forth on this
        continent a new nation, conceived in liberty, and dedicated to the
        proposition that all men are created equal.
     </div>
     <div>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit,
        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
     </div>
</body>
</html>
EOHTML

my $dom = Mojo::DOM->new ;

$dom->parse( $html ) ;

for my $div ( $dom->find( 'div' )->each ) {

    print $div->all_text . "
" ;

}

The output is:

Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...