使用单个正则表达式匹配多行

huangapple go评论58阅读模式
英文:

Matching multiple lines using single regexp

问题

我有一个包含以下内容的文件:

person: male
Pet : dog, cat,

person: female
pet : dog, pig

类似这样的数据有很多人。
我想要获取只有男性的人和他们的宠物数据。
像这样:

person: male
Pet : dog, cat,

我正在尝试匹配两行。但这不起作用。

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

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
    }

 }

答案1

得分: 2

你的问题是你每次只读取一行。如果你使用read一次性读取整个文件,就可以进行多行匹配。

如果你需要进行多行匹配,你可能会发现regexp-line选项很有用,因为它意味着只有在模式中明确放入一个换行符时才会匹配换行符。

英文:

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.

huangapple
  • 本文由 发表于 2023年2月9日 00:54:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75389135.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定