0

I have the following contents in the file:

This is line one
This is line two with string1 and string3
This is line three with string3

I need to replace 'string1' with 'string2' if the line contains 'string3', so that the result would be:

This is line one
This is line two with string2 and string3
This is line three with string3
Starfish
  • 667
  • 1
  • 4
  • 16
  • @wiktor stribizew, This is not duplicate of 'Regex: Remove lines containing'. I do not want to remove lines. – Starfish May 18 '17 at 06:52
  • @WiktorStribiżew The approach may be, but if there is someone out there trying to find a solution to the problem I am facing, they will not be searching for 'remove lines containing'. – Starfish May 18 '17 at 07:05
  • Ok, so what is your problem? Where are you stuck? Also, you have not explained *where* the `string3` may appear. From your examples, it seems that `string3` should *follow* `string2, is that so? – Wiktor Stribiżew May 18 '17 at 07:07
  • 1
    @WiktorStribiżew: I agree with Starfish, this is not *an exact duplicate of an existing question*... – Gawil May 18 '17 at 08:01
  • 2
    @Starfish: Try this, it worked for me on notepad++ : https://regex101.com/r/4L5Wyx/1 – Gawil May 18 '17 at 08:15
  • @Gawil Thank you, that worked for me. – Starfish May 18 '17 at 09:16

2 Answers2

1

To replace all occurrences of string1 on any line that contains string3 anywhere on that line, you need to use a \G based regex:

(?:\G(?!^)|^(?=.*string3)).*?\Kstring1

Replace with string2. See the regex demo online.

Details:

  • (?:\G(?!^)|^(?=.*string3)) - either the end of the previous match or a start of a line that contains string3 in it
  • .*? - any 0+ chars other than line breaks
  • \K - a match reset operator discarding all the text matched so far in the current iteration
  • string1 - a string1 substring to be replaced.

The following text

This is line string1
This is line two with string1 and string3 string1
This is line two with string1 string1 and string3 
This is line three with string3
This is line string3 with string1 and string1

turns into

enter image description here

Graham
  • 6,577
  • 17
  • 55
  • 76
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
0

On behalf of @Gawil

On Notepad++ Go to Search->Replace

Under 'Find what': ^(?=.*?string3)(.*?)string1(.*?)$

Under 'Replace with': \1string2\2

Perform 'Replace' or 'Replace All' as necessary. enter image description here

Starfish
  • 667
  • 1
  • 4
  • 16