在批处理脚本中从字符串中提取前导数字 [英] Extract leading numbers from a string in batch script
本文介绍了在批处理脚本中从字符串中提取前导数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是批量脚本的新手。虽然我有这个问题的shell和python解决方案,但陷入批处理脚本。
I am new to batch scripting. although i have shell and python solutions for this problem but got stuck in batch script.
我有字符串 123_happy
, 234.healthy
, 3456wealthy
等。
想从每个字符串中提取前导数字。
I want to extract the leading numbers from each string. the only pattern here is that all these strings contain numbers in the beginning.
我不能使用echo %str:〜0,3%
,因为它不符合我的要求。
I can't use echo %str:~0,3%
as it doesn't fulfill my requirement.
推荐答案
循环(1 => 1000应该就足够了)对变量的字符,找到第一个字符不在数字范围。提取之前的子字符串:
Loop (1=>1000 should be enough ;)) on the characters of the variable and find the first char not in number range. Extract the substring before:
@echo off
set z=123_happy
setlocal enabledelayedexpansion
set result=
for /L %%i in (0,1,1000) do (
set zz=!z:~%%i,1!
if x!zz!==x exit /b
if !zz! lss 0 (
set result=!z:~,%%i!
goto out
)
if !zz! gtr 9 (
set result=!z:~,%%i!
goto out
)
)
:out
echo result=!result!
结果:
result=123
这篇关于在批处理脚本中从字符串中提取前导数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文