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
,
What about this:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define the string here:
set "STR=123_happy"
setlocal EnableDelayedExpansion
rem // Get first character behind the numeric part:
for /F delims^=0123456789^ tokens^=*^ eol^= %%F in ("!STR!") do (
endlocal
set "SEP=%%F"
setlocal EnableDelayedExpansion
if defined SEP set "SEP=!SEP:~,1!"
)
rem // Split the string at the character behind the numeric part:
if not defined SEP goto :SKIP
for /F eol^=^%SEP%^ delims^=^%SEP% %%N in ("0!STR!") do (
endlocal
set "STR=%%N"
setlocal EnableDelayedExpansion
set "STR=!STR:~1!"
)
:SKIP
rem // Return the numeric part:
echo(!STR!
endlocal
endlocal
exit /B
The basic idea is to get the first character after the numeric part, which is the used as the delimiter for a for /F
loop parsing the input string. This has got the great advantage that the limit for signed 32-bit integers does not apply, opposed to the approaches using set /A
or for /L
. In addition, leading zeros do not lead to unintentional interpretation as octal numbers, since this script treats the numeric part as string.