Extract leading numbers from a string in batch script

后端 未结 6 1634
灰色年华
灰色年华 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条回答
  •  -上瘾入骨i
    2021-01-03 00:25

    probably the easiest and the fastest way:

    set z=123_happy
    for /l %%# in (%z%,1,%z%) do echo %%#
    

    this will leave only the leading numbers.Though it is limited to 32b integers. As a subroutine (will fail if the input contains delimiters):

    :extractLeadingNumbers input [rtrnVar]
      for /l %%# in (%~1;1;%~1) do (
         if "%~2" neq "" (
           set "%%#=%~2"
         ) else (
           echo %%#
         )
      )
    

    More robust way (which will also remove leading zeroes):

    cmd /c exit /b 123_happy
    echo %errorlevel%
    

提交回复
热议问题