问题
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