在批处理文件中,我有一个字符串abcdefg。我想检查bcd是否在字符串中。
不幸的是,似乎所有的解决方案,我找到搜索一个文件的子字符串,而不是一个字符串的子字符串。
有没有简单的解决方法?
在批处理文件中,我有一个字符串abcdefg。我想检查bcd是否在字符串中。
不幸的是,似乎所有的解决方案,我找到搜索一个文件的子字符串,而不是一个字符串的子字符串。
有没有简单的解决方法?
当前回答
ECHO %String%| FINDSTR /C:"%Substring%" && (Instructions)
其他回答
对我来说最好的方法是:
call :findInString "HelloWorld" "World"
:findInString
ECHO.%1 | FIND /I %2>Nul && (
Echo.Found
) || (
Echo.Not found
)
更好的答案是:
set "i=hello " world"
set i|find """" >nul && echo contains || echo not_contains
ECHO %String%| FINDSTR /C:"%Substring%" && (Instructions)
我通常是这样做的:
Echo.%1 | findstr /C:"%2">nul && (
REM TRUE
) || (
REM FALSE
)
例子:
Echo.Hello world | findstr /C:"world">nul && (
Echo.TRUE
) || (
Echo.FALSE
)
Echo.Hello world | findstr /C:"World">nul && (Echo.TRUE) || (Echo.FALSE)
输出:
TRUE
FALSE
我不知道这是不是最好的办法。
您可以将源字符串输送到findstr,并检查ERRORLEVEL的值,以查看是否找到了模式字符串。值为0表示成功,并且找到了模式。这里有一个例子:
::
: Y.CMD - Test if pattern in string
: P1 - the pattern
: P2 - the string to check
::
@echo off
echo.%2 | findstr /C:"%1" 1>nul
if errorlevel 1 (
echo. got one - pattern not found
) ELSE (
echo. got zero - found pattern
)
当在CMD.EXE中运行时,我们得到:
C:\DemoDev>y pqrs "abc def pqr 123"
got one - pattern not found
C:\DemoDev>y pqr "abc def pqr 123"
got zero - found pattern