简体   繁体   中英

Regex New Line No Match

I'm trying to screen scrape some HTML and am having trouble matching across a new line (in .Net)

This is the text:

<td class=abc><span class=label>XXX</span></td>
<td class=def><span class=field>YYY</span></td>

I'm trying to match YYY with this formula

<td class=abc><span class=label>XXX</span></td>\n<td class=def><span class=field>(.*)</span></td>

I have \\n separating the lines, but it doesn't match... Any ideas?

[EDIT]

Added \\r\\n instead of just \\n and it worked.

You need to use the multi-line modifier m for your regex. In VB.NET this is supplied as an option for a regex expression. But you also need to escape all forward-slashes using a backslash:

<td class=abc><span class=label>XXX<\/span><\/td>\n<td class=def><span class=field>(.*)<\/span><\/td>

Please note, though, that regex is a very poor way to parse HTML - there are HTML parsers in most languages that do a much better job.

And your regex is very detailed and, therefore, brittle; an additional space would cause it to fail.

Note that in Windows newlines are typically created with a carriage-return and newline combination \\r\\n .

Here is an example supplying the Multiline option:

Dim rex As New Regex("\bsomething\b", RegexOptions.MultiLine)

Regex Options :MSDN

Here I write perl code but in if condition ,used \n new line character not match  



  #!/usr/bin/perl
    use strict;
    #use warnings;
    use Cwd;
    use File::Basename;
    use File::Copy;

    my $path=getcwd;    
    #print $path."\n";
    opendir(INP, "$path\/");
    my @out = grep(/.(xml)$/,readdir(INP));
    close INP;
    #print @out;
    open(F6, ">Log.txt");
    foreach my $f1(@out)
    {
        open(FF, "<$path\/$f1") or die "Cannot open file: $out[0]";
        my $data1 = join("", <FF>); 
        my @FILE_KA_ARRAY = split(/\n/, $data1);
        my $file_ka_len = @FILE_KA_ARRAY;
        #print F6 $file_ka_len."\n";
        #print F6 $f."\t".$file_ka_len."\n";
        print F6 $f1."\n";
        for(my $x=1; $x<$file_ka_len; $x++)
        {   
            my $y=$x+1;
            my $temp_file_arr = ""; 
            $temp_file_arr = $FILE_KA_ARRAY[$x];
        #print F6 $temp_file_arr."\t$x\n";
        my $temp1=$temp_file_arr;
    if($temp1=~m#(<list .*? depth="(\d+)">)\n?(<list .*? depth="(\d+)">)#gs)
    {
    my $list3=$1;
    print F6 "\t\t\t\t\t\t\t\t".$y."\t\t".$list3."\n";
    }
    }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM