从批处理脚本中的字符串中提取前导数字

ASR*_*ASR 6 cmd batch-file

我是批处理脚本的新手.虽然我有这个问题的shell和python解决方案,但陷入批处理脚本.

我有串像123_happy,234.healthy,3456wealthy等等.

我想从每个字符串中提取前导数字.这里唯一的模式是所有这些字符串在开头都包含数字.

我不能使用echo,%str:~0,3%因为它不符合我的要求.

Aac*_*ini 11

我认为这是最简单的方法:

@echo off
setlocal

set "str=123_happy"
set /A num=str
echo Result = %num%
Run Code Online (Sandbox Code Playgroud)

set /A命令从变量中获取值时,它会将数字转换为第一个非数字字符而没有错误.

保留左零:

set "str=0128_happy"
set "num=1%str%"
set /A num=num
set "num=%num:~1%"
echo Result = %num%
Run Code Online (Sandbox Code Playgroud)


MC *_* ND 7

只是另一种选择

@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
Run Code Online (Sandbox Code Playgroud)


npo*_*aka 7

可能是最简单,最快捷的方式:

set z=123_happy
for /l %%# in (%z%,1,%z%) do echo %%#
Run Code Online (Sandbox Code Playgroud)

这将只留下前导数字.尽管它仅限于32b整数.作为子例程(如果输入包含分隔符,则会失败):

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

强大的方式(也将删除前导零):

cmd /c exit /b 123_happy
echo %errorlevel%
Run Code Online (Sandbox Code Playgroud)