Page 1 of 1

Find backward in a variable

Posted: 2021-Aug-16, 12:50 pm
by darwin4ever
Lets assume a variable contains an URL, something like

Code: Select all

https://a_site.com/wp-content/uploads/2020.07/image001.jpg
I need to extract the image-extension i.e. in this case the ".jpg"

Attention
- the length or the URL is never the same
- the number of "." (dots) in the URL before the dot in ".jpg" can vary
- the extension could also be ".anythingelse"

Meaning I need to find a way to locate the last "." (the first backward) to extract everything after it

Any ideas how I could do that ?

Thanks

Re: Find backward in a variable

Posted: 2021-Aug-16, 2:17 pm
by darwin4ever
I found a way to do it, but maybe there is a better solution.

In the meanwhile I reverse the URL, then take the part till the first token (dot) and then reverse it again.

Code: Select all

SET URLNameSource=%1
call :ReverseString %URLNameSource%
for /f "tokens=1 delims=." %%i in ("%ReverseOutputString%") do (set prefix=%%i)
call :ReverseString %prefix%
echo %ReverseOutputString%

EXIT /B

:ReverseString

SET ReverseInputString=%1
SET ReverseOutputString=
SET num=0
:ReverseStringLoop
CALL SET TempChar=%%ReverseInputString:~%num%,1%%%
SET /a num+=1
if defined TempChar (
    set ReverseOutputString=%TempChar%%ReverseOutputString%
    goto :ReverseStringLoop
)

Re: Find backward in a variable

Posted: 2021-Aug-16, 4:35 pm
by Simon Sheppard
Here's a previous thread about this:

extract file name extension from environment var

Re: Find backward in a variable

Posted: 2021-Aug-23, 7:44 am
by darwin4ever
Thanks ! Works !

I first thought the %~1 would only work on filenames, not URL's, but it does.
So that's great and simple