Reputation: 67420
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:
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.
Upvotes: 1
Views: 369
Reputation: 626950
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 regex demo. The regex above matches the last non-whitespace char on a line (capturing it in Group 1 to keep it), then matches horizontal whitespace (if any) and then captures a line break that is also captured to keep in the output.
Details
(\S)
- Group 1: any non-whitespace char[^\S\n]*
- zero or more horizontal whitespace chars(\n)
- Group 2: line break.$
- end of a line (note that m
flag (in its PCRE meaning) is always on, by default, in VSCode regex).The replacement is $1<br><br>$2
, Group 1 value + <br><br>
+ Group 2 value (if you use the first regex).
is changed into
Upvotes: 3
Reputation: 181639
This works to retain the spaces at the end of lines:
Find: (?<=^.*)(\S+.*)
Replace: $1<br><br>
Upvotes: 1