How do I zero-pad issue numbers without changing the # prefix?
Answer
:%s/#\zs\d\+/\=printf('%04d', submatch(0))/g
Explanation
For log files, changelogs, or issue references, you sometimes need fixed-width numeric IDs without touching surrounding syntax. This substitution uses a pattern boundary plus an expression replacement, so only the number is rewritten while the # marker stays intact.
How it works
:%s/#\zs\d\+/\=printf('%04d', submatch(0))/g
:%s/.../.../gruns substitution on the whole buffer#\zs\d\+matches digits that come after#;\zsmoves the effective start of the match to just the digits\=printf('%04d', submatch(0))evaluates Vimscript for each match and left-pads the number to width 4gupdates every ticket-like match on each line
Because \zs narrows the replacement target, the prefix character is never captured or rewritten. That makes this safer than broader capture-group substitutions when formats vary.
Example
Before:
Fixes #7 and #42; supersedes #1002.
After:
Fixes #0007 and #0042; supersedes #1002.
Tips
- Change
%04dto%06d(or any width) for your convention - Use a more specific prefix (for example
TICKET-) if your file contains other#uses - Drop
%and use a visual or line range when you only want part of the file