I am new to batch scripting. although i have shell and python solutions for this problem but got stuck in batch script.
I have string like 123_happy
, 234.healthy
, 3456wealthy
etc.
I want to extract the leading numbers from each string. the only pattern here is that all these strings contain numbers in the beginning.
I can't use echo %str:~0,3%
as it doesn't fulfill my requirement.
I think this is the simplest way:
@echo off
setlocal
set "str=123_happy"
set /A num=str
echo Result = %num%
When set /A
command get a value from a variable, it convert the number until the first non-digit character with no error.
To preserve left zeros:
set "str=0128_happy"
set "num=1%str%"
set /A num=num
set "num=%num:~1%"
echo Result = %num%
Just another option
@echo off
setlocal enableextensions disabledelayedexpansion
call :extractLeadingNumbers 123_happy leadingNumbers
echo %leadingNumbers%
call :extractLeadingNumbers 234.healthy leadingNumbers
echo %leadingNumbers%
call :extractLeadingNumbers "3456wealthy" leadingNumbers
echo %leadingNumbers%
goto :eof
rem This extracts the first numerical serie in the input string
:extractLeadingNumbers inputString returnVar
setlocal enableextensions disabledelayedexpansion
rem Retrieve the string from arguments
set "string=%~1"
rem Use numbers as delimiters (so they are removed) to retrieve the rest of the string
for /f "tokens=1-2 delims=0123456789 " %%a in ("%string:^"=%") do set "delimiters=%%a%%b"
rem Use the retrieved characters as delimiters to retrieve the first numerical serie
for /f "delims=%delimiters% " %%a in ("%string:^"=%") do set "numbers=%%a"
rem Return the found data to caller and leave
endlocal & set "%~2=%numbers%"
goto :eof
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With