Home > Enterprise >  (Notepad ) How do I use Regex to remove everything in a file before a word, but NOT including the w
(Notepad ) How do I use Regex to remove everything in a file before a word, but NOT including the w

Time:12-26

I have a file that has lots of lines and I have one line that starts with "1020":

990.1.1={
    holder=1000083706 #Dowelani
}
1020.1.1={
    holder=1000083707 #Mutsutshudzi
}
1050.1.1={
    holder=1000083708 #Khathu
}

I want to remove every line above that line starting with 1020, but I want to keep the 1020 line.

I have been trying .*1020, and this removes everything before the line containing "1020", but it also removes the 1020. How can I modify the code to keep the line I search for but also remove every line above it?

CodePudding user response:

Rather that discarding the part of the string up to the target string it's easier to simply match the line that begins with the target string and all subsequent lines. You can do that with the regular expression

^1020\..*

with the multiline and single line (or dotall) flags set.

Demo

The multiline flag causes ^ to the match the beginning of a line, rather than the beginning of the string, and the single line flag causes . to match every character, including line terminators. (Without that flag set . matches all characters other than line terminators.)

If you only want to keep the (first) line that begins with the target string, do not set the single-line flag and return the first match (using re.search()).

CodePudding user response:

You can use

Find What: (?s)^.*?\R(?=1020\.)
Replace With: empty string

See the regex demo. Details:

  • (?s) - a dot now matches newlines, too
  • ^ - start of a line
  • .*? - any zero or more chars, as few as possible
  • \R - a line break sequence
  • (?=1020\.) - a positive lookahead that matches a location in string that is immediately followed with 1020..
  • Related