字符串开头的批处理文件

时间:2016-03-25 21:38:57

标签: batch-file

我需要知道一个字符串是否以某种东西开头,产生了这个小例子来解释(我使用批处理编译器/预处理器或任何高级命令):

rem GetInput
if "%result%"=="cd *" goto Cd
:Cd
if "%result%"=="cd meow" Echo Going to directory 'meow'...

但是这段代码不适用于" cd *"脚本不要去:如果字符串%result%以字母cd开头,则为Cd。 不知道我现在是否真的可以理解但是会喜欢一些帮助x)

谢谢,

- 方

2 个答案:

答案 0 :(得分:3)

如果我理解正确,您可以尝试确定%result%的值是否以' cd'开头,并且您使用{{1}时未成功}作为通配符来确定这一点。

有几种不同的方法可以解决这个问题。这是一种方法:您可以检查前两个字符是否等于' cd':

*

if /i "%result:~0,2%"=="cd" goto Cd 对此有更多了解。

答案 1 :(得分:0)

here's一个相对健壮且通用的startsWith子例程(有两个例子)。如果字符串以另一个字符串开头,则将errorlevel设置为1,如果没有,则设置为0。

@echo off
set string1=abc123123
set checker1=abc

call :startsWith %string1% %checker1%
if %errorlevel% equ 1 (
    echo %string1% starts with %checker1%
) else (
    echo %string1% does NOT start with %checker1%
)

set string2=xyz123123 abc

call :startsWith %string2% %checker2%
if %errorlevel% equ 1 (
    echo %string2% starts with %checker2%
) else (
    echo %string2% does NOT start with %checker2%
)




exit /b 0

::::::::::::::::::::::::::::::::::::::::
:::----- subroutine starts here ----::::
:startsWith [%1 - string to be checked;%2 - string for checking ] 
@echo off
rem :: sets errorlevel to 1 if %1 starts with %2 else sets errorlevel to 0

setlocal EnableDelayedExpansion

set "string=%~1"
set "checker=%~2"
rem set "var=!string:%~2=&echo.!"
set LF=^


rem ** Two empty lines are required
rem echo off
for %%L in ("!LF!") DO (
    for /f "delims=" %%R in ("!checker!") do ( 
        rem set "var=!string:%%~R%%~R=%%~L!"
        set "var=!string:%%~R=#%%L!"
    )
)
for /f "delims=" %%P in (""!var!"") DO (
    if "%%~P" EQU "#" (
        endlocal & exit /b 1
    ) else (
        endlocal & exit /b 0
    )
)
::::::::::::::::::::::::::::::::::::::::::::::::::
相关问题