REGEX - Matching again multiple lines

徘徊边缘 提交于 2019-12-11 17:54:18

问题


Given text like:

XXXXXXX. XXXXXXX. XXXXXXX. XXXXXXX. XXXXXXX. XXXXXXX. XXXXXXX. XXXXXXX. XXXXXXX.XXXXXXX. XXXXXXX. XXXXXXX. XXXXXXX. XXXXXXX. XXXXXXX. XXXXXXX. XXXXXXX. XXXXXXX.XXXXXXX. XXXXXXX. XXXXXXX. XXXXXXX. XXXXXXX. XXXXXXX. XXXXXXX. XXXXXXX. XXXXXXX.

Boss: asdasdasdasd
Date: XXX, XXXXXXXXX

I want to match the last 3 lines:

Here's what I'm trying but it's failing:

^Boss:.*$^Date:.*$

Suggestions? Thanks


回答1:


You might need to skip the first x lines... also you anchor ^ is probably causing you not to match.

Try

(?:.*[\r\n]*)*Boss:.*(?:.*[\r\n]*)Date:.*



回答2:


^Boss:.*[\r\n]+Date:.*$

The line anchors, ^ and $, are zero-width assertions; they assert that some condition holds true without consuming any characters.

  • ^ means the current position is either the beginning of the input, or it's immediately preceded by a line separator.
  • $ means the current position is either the end of the input, or it's immediately followed by a line separator.

But neither of them consumes the line separator, so $^ can never match. [\r\n]+ matches (and consumes) one or more carriage-returns or linefeeds, so it handles the three most common types of line separator: \r (older Mac standard), \r\n (Windows/network standard), and \n (Unix/Linux/Mac OS X/pretty much everything else).




回答3:


If your file is not of size in GB range

ruby -e 'a=File.read("file"); p a.split(/\n/)[-3..-1] '


来源:https://stackoverflow.com/questions/4975459/regex-matching-again-multiple-lines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!