Add leading zeros to filename to all be 12 max characters?

A swapping-ground for Regular Expression syntax

Add leading zeros to filename to all be 12 max characters?

Postby mawaybe » Mon Apr 10, 2023 7:59 pm

Hi:

So I've seen some topics that get close to this but cannot figure out the rest. Any help is much appreciated!

Here's what I have... hundreds of files with names like this.

2314.jpg
022614.jpg
00231564.jpg
003600528530.jpg

So the names can be 3,4 or anything up to 12 characters in length.

What I need to do is convert those filenames by adding leading zeros to ALL be 12 characters in length like this.

000000002314.jpg
000000022614.jpg
000000231564.jpg
003600528530.jpg

It seems there should be a regex way to do this but it's beyond me. Easy to do in Excel - just use... =text(A1,"000000000000") ...and concatenate the ".jpg".

Thanks in advance for your help!
mawaybe
 
Posts: 2
Joined: Mon Apr 10, 2023 7:46 pm

Re: Add leading zeros to filename to all be 12 max characters?

Postby Admin » Mon Apr 10, 2023 11:56 pm

Hi, this will work with JavaScript Renaming

Code: Select all
const maxdigits=12;
newName = ('00000000000000000000000000000000'+name).slice(-maxdigits);
Admin
Site Admin
 
Posts: 2354
Joined: Tue Mar 08, 2005 8:39 pm

Pad all numbers to 12-digits

Postby Luuk » Tue Apr 11, 2023 5:19 am

Greetings everyone! Also with Regex(1) having a checkmark inside for "v2", the "Match" and "Replace" can be like...
^(?=\d+$)(?X)\G\K0(?=\d{12,}$)/g
00000000000(?X)

The (?X) is used to separate many different regexs, so they can be conducted with only 1-rename.
The 1st-regex to verify that filenames should have only digits, so then it just prefixes 11-zeros.
The 2nd-regex will then delete any leading zeros, when there is 12-or-more digits before the end.
Luuk
 
Posts: 706
Joined: Fri Feb 21, 2020 10:58 pm

Re: Add leading zeros to filename to all be 12 max characters?

Postby mawaybe » Tue Apr 11, 2023 7:36 pm

Hi

Thank you both for your replies! Javascript is a bit beyond me - sorry - but the Regex solution worked great.

SOLVED!

Thanks again!
mawaybe
 
Posts: 2
Joined: Mon Apr 10, 2023 7:46 pm


Return to Regular Expressions