So, I have a lot of numbers in lines like so
rocket123
firefly1000
attack577
Is there any regex to make the numbers reversed?
rocket321
firefly0001
attack775
So, I have a lot of numbers in lines like so
rocket123
firefly1000
attack577
Is there any regex to make the numbers reversed?
rocket321
firefly0001
attack775
This is feasible with a little trick.
Step 1. Add a marker for the not-yet-inverted digits.
Find:
\b(\w+?)(\d+)\b
Replace:
$1§$2
You can choose other marker instead of §
.
Step 2. Do Replace all enough times with these settings:
Find:
\b(\w+)§(\d*)(\d)\b
Replace:
$1$3§$2
Step 3. Delete all markers.
Find:
\b(\w+\d)§
Replace:
$1
Hope this helps.
If the maximum number of digits to be reversed is known and not too large then a single Notepad++ regular expression search and replace can be used. Suppose the maximum number of digits is 12 then the expressions are:
Search for:
(\d)(\d)(\d)?(\d)?(\d)?(\d)?(\d)?(\d)?(\d)?(\d)?(\d)?(\d)?
Replace with:
(?{12}${12})(?{11}${11})(?{10}${10})(?9$9)(?8$8)(?7$7)(?6$6)(?5$5)(?4$4)(?3$3)$2$1
Explanation:
Any number to be reversed must have at least two digits, so the initial (\d)(\d)
in the search gets two digits and the final $2$1
in the replace puts them in reverse order at the end of the output. (The first two digits are the easy part.) The search string then repeats the pattern (\d)?
as many times as needed for the maximum number of digits. These match the remaining digits, if any. Each of these (\d)?
patterns has a corresponding item in the replace string, they are of the form (?N$N)
where each N
is the number of the capture group. Single digit captures are like (?4$4)
for number 4. For captures 10 and above the number is wrapped in curly braces, such as (?{12}${12})
for number 12. These replacement items test whether a capture group captured anything and, if it did then insert that captured item. See also this answer.
Variations
Add or remove additional search and replacement items as needed for longer or shorter maximum numbers of digits.
If the number of digits might be larger than expected then adding an extra (\d)?
to the search string and (?{13}__Some suitable error message__)
to the end of the replacement will output the error message on overlong groups of digits. Of course the 13
needs to be altered to match the number of items in search and replacement.
Tested with Notepad++ version 7.5.6.