find search item plus 4 lines before and after

2019-04-13 11:01发布

问题:

I am using notepad++ and would like to find the context in which a particular string occurs.

So the search string is 0wh.*0subj and I would like to find this search item plus 4 lines immediately before and after it.

eg: xxx means whatever is on a new line. the search result should be:
xxx
xxx
xxx
xxx
0wh.*0subj
xxx
xxx
xxx
xxx

I have tried using \n\r but its not working. Any assistance afforded would be greatly appreciated.

Regards

回答1:

This will work in Notepad++ (tested):

(?m)(^[^\r\n]*\R+){4}0wh\.\*0subj[^\r\n]*\R+(^[^\r\n]*\R+){4}

On the screenshot, note that the 555 line is not selected. It is just the current line.

Explain Regex

(?m)                     # set flags for this block (with ^ and $
                         # matching start and end of line) (case-
                         # sensitive) (with . not matching \n)
                         # (matching whitespace and # normally)
(                        # group and capture to \1 (4 times):
  ^                      #   the beginning of a "line"
  [^\r\n]*               #   any character except: '\r' (carriage
                         #   return), '\n' (newline) (0 or more times
                         #   (matching the most amount possible))
  \R+                    #   'R' (1 or more times (matching the most
                         #   amount possible))
){4}                     # end of \1 (NOTE: because you are using a
                         # quantifier on this capture, only the LAST
                         # repetition of the captured pattern will be
                         # stored in \1)
0wh                      # '0wh'
\.                       # '.'
\*                       # '*'
0subj                    # '0subj'
[^\r\n]*                 # any character except: '\r' (carriage
                         # return), '\n' (newline) (0 or more times
                         # (matching the most amount possible))
\R+                      # 'R' (1 or more times (matching the most
                         # amount possible))
(                        # group and capture to \2 (4 times):
  ^                      #   the beginning of a "line"
  [^\r\n]*               #   any character except: '\r' (carriage
                         #   return), '\n' (newline) (0 or more times
                         #   (matching the most amount possible))
  \R+                    #   'R' (1 or more times (matching the most
                         #   amount possible))
){4}                     # end of \2 (NOTE: because you are using a
                         # quantifier on this capture, only the LAST
                         # repetition of the captured pattern will be
                         # stored in \2)