Bob
Bob

Reputation: 63

Replace all occurrences of a character between two strings

I want to replace all space occurrences between string1 and string2 with a _ character on all lines of a text document using Notepad++.

Examples:

string1 this is a first example string2
string1 this is a second example string2

Expected result:

string1_this_is_a_first_example_string2
string1_this_is_a_second_example_string2

I tried this expression (?<=string1)(\s*)(?=string2), but it didn't work.

Upvotes: 3

Views: 1506

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627327

You may use

Find What: (?:\G(?!^)|string1)(?:(?!string1|string2).)*?\K\h(?=.*string2)
Replace With: _

See the regex demo.

NOTE:

  • If you need to only match regular spaces, replace \h with a regular space
  • A more appropriate check for the end of the previous successful match is \G(?!^(?<![\s\S])), but if your expected matches are on a single line, you might go on using \G(?!^).

Details

  • (?:\G(?!^)|string1) - either the end of the previous match (but not start of a line) or string1
  • (?:(?!string1|string2).)*? - any char, 0 or more times, but as few as possible, that is not starting string1 or string2 char sequence
  • \K - discard the text matched so far
  • \h - any horizontal whitespace
  • (?=.*string2) - there must be a string2 after any 0 or more chars other than line break chars as many as possible immediately to the right of the current location.

enter image description here

Upvotes: 3

Related Questions