Search code examples
regextclfile-handling

Matching multiple lines using single regexp


I have a file which contains

person: male

Pet : dog, cat,

person: female

pet : dog, pig

Like this many persons data is there I want to get data of only male persons. and their pet. Like

person: male

Pet : dog, cat,

I am trying to match two line. Thats not working

    while{[gets $fh line] > 0} {
     if {[regexp {(person: male.*)\n(pets :.*)} $line match submatch]} {
    puts $match 
    puts $submatch
    }

 }

Solution

  • Your problem is that you are only reading one line at a time. If you read the whole file in (with read) then you can do multiline matching.

    If you are doing multiline matching, you might find the -line option to regexp useful, as it means it will only ever match a newline if you explicitly put one in the pattern.