英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论