Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - Renaming file to highest resolution in filename

Tags:

regex

file

rename

I'm using an application called Advanced Renamer to rename my video files. I try to rename video files by selecting the highest quality available, which is specified inside the current filename itself.

For example an original untoched filename looks like: 1080P,720P,480P,240P,_123456789.mp4

Im using regex to rename this example file to: 1080P_123456789.mp4.

However, the result of the regex I'm using right now .*(?=1080P|720P|480P|240P) does not work properly, it's taking the lowest quality instead of the highest: 240P,_123456789.mp4

Correct examples:

1080P,720P,480P,240P,_0987654321.mp4  --> 1080P_0987654321.mp4
720P,480P,_0987654321.mp4             --> 720P_0987654321.mp4
480P,240P,_0987654321.mp4             --> 480P_0987654321.mp4

Wrong examplesmy regex is giving me:

1080P,720P,480P,240P,_0987654321.mp4  --> 240P_0987654321.mp4
720P,480P,_0987654321.mp4             --> 480P_0987654321.mp4
480P,240P,_0987654321.mp4             --> 240P_0987654321.mp4

Edit: Solution

^.*?(1080P|720P|480P|240P).*?(_\d+\.mp4).*$
OR 
^.*?(\d+P).*?_(\d+\.mp4)\S*
OR
.*?(\d+P)[^.]*_(\d+\.mp4)\S*
like image 797
Johanthan Avatar asked Nov 20 '25 15:11

Johanthan


2 Answers

Try this ^(1080P|720P|480P|240P).*,(.*). The ^ will match the first occurance in the line.

like image 176
Eraklon Avatar answered Nov 23 '25 05:11

Eraklon


For the current example data, you could capture the first occurrence in a capturing group as that is the highest value.

Then match any char except an underscore afterwards using a negated character class followed by an underscore to make sure it is there.

\b(\d+P)\b[^_]*_

Explanation

  • \b Word boundary
  • (\d+P) Capture group 1, match 1+ digits and P
  • \b Word boundary
  • [^_]*_ Match 0+ times any char except _, then match an _

Regex demo

In the replacement use the first capturing group followed by the matched underscore which was part of the match and is not present in the capturing group.


If you also want to remove what comes before the digits and P and after .mp4 with the specific numbers:

^.*?(1080P|720P|480P|240P).*?(_\d+\.mp4).*$

Regex demo

In the replacement use both capturing groups $1$2

like image 42
The fourth bird Avatar answered Nov 23 '25 05:11

The fourth bird