Home > Back-end >  Using a regex to append to the end of non-blank lines
Using a regex to append to the end of non-blank lines

Time:11-06

I would think that this would be a common question, but I can't find anybody asking how to do this. There are people asking how to do the opposite (find blank lines) and add a <br><br> at the end of each one. For human readability, this document has blank lines between paragraphs.

(I don't want to replace the blank lines with <br><br>. I know this would achieve the same result, but for human readability and personal preference, I don't like how this makes the document one giant block of text.)

How can I write a regex that captures -- I don't know if this is the right word to use; maybe "groups"? -- the end of lines that aren't blank so that I can append to the end of them?

I am using Visual Studio code, so I'd like this to work in the search/replace box:

enter image description here

I'm assuming in the replacement box above, I'd need to say $some group number(s?), so I just said $x as a temporary placeholder. Here's what I've tried as search patterns:

^(?!:($))$
^(?!:(\S$))$
^(?!:([^\S]$))$
^(?!:([^\s]$))$
^(?!([^\S] ))$

All of these seem to grab the inverse of what I'm trying to find. I guess my strategy has been, between the beginning and end of the line, there shouldn't be only whitespace. But I'm pretty sure that's not what I'm saying.

CodePudding user response:

You can use

Find What:      (\S)[^\S\n]*(\n)
Replace With: $1<br><br>$2

NOTE: The above replacement will not add the <br>s at the end of the last line if it is not blank. If you need that, use

Find What:      (\S)[^\S\n]*$
Replace With: $1<br><br>

See the enter image description here

is changed into

enter image description here

CodePudding user response:

This works to retain the spaces at the end of lines:

Find: (?<=^.*)(\S .*)

Replace: $1<br><br>

enter image description here

  • Related