Extract leading numbers from a string in batch script

后端 未结 6 1653
灰色年华
灰色年华 2021-01-02 23:39

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,

6条回答
  •  佛祖请我去吃肉
    2021-01-03 00:20

    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
    

提交回复
热议问题