user500665
user500665

Reputation: 1362

Remove all spaces from lines starting with specific word

Using Regex find/replace in Notepadd++ how can I remove all spaces from a line if the line starts with 'CHAPTER'?

Example Text:

CHAPTER A B C
Once upon a time.

What I want to end up with:

CHAPTERABC
Once upon a time.

Incorrect code is something like:

(?<=CHAPTER)( )(?<=\r\n)

So 'CHAPTER' needs to stay and the search should stop at the first line break.

Upvotes: 1

Views: 214

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626826

You may use a \G based regex to only match a line that starts with CHAPTER and then match only consecutive non-whitespace and whitespace chunks up to the linebreak while omitting the matched non-whitespace chunks and removing only the horizontal whitespace:

(?:^CHAPTER|(?!^)\G)\S*\K\h+

Details:

  • (?:^CHAPTER|(?!^)\G) - CHAPTER at the start of a line (^CHAPTER) or (|) the end of the previous successful match ((?!^)\G, as \G can also match the start of a line, we use the retricting negative lookahead.)
  • \S* - zero or more non-whitespace symbols
  • \K - a match reset operator forcing the regex engine omit the text matched so far (thus, we do not remove CHAPTER or any of the non-whitespace chunks)
  • \h+ - horizontal whitespace (1 or more occurrences) only

enter image description here

Upvotes: 2

Related Questions