I want to replace the end of a line on line with ';' but only on lines that do not already end in ';'. I came up with the following to put in the replace dialog:
Find What = '[^\;]\r\n'
Replace with = '\;\r\n'My problem is that this also selects the last character of a line. I don't want to replace the last character... just the carriage return.
Any ideas on how to correct this?
23 Answers
Your regex as it stands will replace the whole end of the line, so the best bet is to take the whole line, check it for a semi, and only replace the section that needs it (eg add a semi).
(.*)([^\;])(\r\n)is an expression with 3 capture groups:
(.*)-- the first part of the line([^\;])-- the check for the missing semi(\r\n)-- the line ending
So, we can take the first group, add a semi, and then take the last group to get the full line, with the only difference being the semi itself.
the replace expression \1\;\3 will concatenate together the first group, a semi, and the last group.
Note that the \# syntax is common to Notepad++ and some other tools, but is not universal (many use $1, $2,...$n). be sure to check your editors documentation.
Use
Find What: ([^\;])\r\n
Replace with: $1;\r\nIt will replace the last character with the same character + ';' unless it is ';'
Also, in 'replace' '\' is not needed before ';'
- Ctrl+H
- Find what:
(?<!;)$ - Replace with:
; - check Wrap around
- check Regular expression
- Replace all
Explanation:
(?<! # negative lookbehind, zero-length assertion that make sure we haven't before current position: ; # a semicolon
) # end lookbehind
$ # end of line