在批处理文件中,我有一个字符串abcdefg。我想检查bcd是否在字符串中。

不幸的是,似乎所有的解决方案,我找到搜索一个文件的子字符串,而不是一个字符串的子字符串。

有没有简单的解决方法?


当前回答

是的,你可以使用替换并检查原始字符串:

if not x%str1:bcd=%==x%str1% echo It contains bcd

%str1:bcd=%位将str1中的bcd替换为空字符串,使其与原始字符串不同。

如果原始版本中不包含bcd字符串,那么修改后的版本将是相同的。

使用下面的脚本进行测试将显示它的运行情况:

@setlocal enableextensions enabledelayedexpansion
@echo off
set str1=%1
if not x%str1:bcd=%==x%str1% echo It contains bcd
endlocal

以及各种运行的结果:

c:\testarea> testprog hello

c:\testarea> testprog abcdef
It contains bcd

c:\testarea> testprog bcd
It contains bcd

几点注意事项:

if语句是这个解决方案的核心,其他的都是支持的东西。 等式两边前面的x是为了确保字符串bcd正常工作。它还可以防止某些“不适当的”开头字符。

其他回答

我给出这个答案可能有点晚了,但接受的答案只适用于检查“硬编码字符串”是否是搜索字符串的一部分。

对于动态搜索,你必须这样做:

SET searchString=abcd1234
SET key=cd123

CALL SET keyRemoved=%%searchString:%key%=%%

IF NOT "x%keyRemoved%"=="x%searchString%" (
    ECHO Contains.
)

注意:您可以将这两个变量作为参数。

更好的答案是:

set "i=hello " world"
set i|find """" >nul && echo contains || echo not_contains

您可以将源字符串输送到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

是的,你可以使用替换并检查原始字符串:

if not x%str1:bcd=%==x%str1% echo It contains bcd

%str1:bcd=%位将str1中的bcd替换为空字符串,使其与原始字符串不同。

如果原始版本中不包含bcd字符串,那么修改后的版本将是相同的。

使用下面的脚本进行测试将显示它的运行情况:

@setlocal enableextensions enabledelayedexpansion
@echo off
set str1=%1
if not x%str1:bcd=%==x%str1% echo It contains bcd
endlocal

以及各种运行的结果:

c:\testarea> testprog hello

c:\testarea> testprog abcdef
It contains bcd

c:\testarea> testprog bcd
It contains bcd

几点注意事项:

if语句是这个解决方案的核心,其他的都是支持的东西。 等式两边前面的x是为了确保字符串bcd正常工作。它还可以防止某些“不适当的”开头字符。

建立在@user839791的答案上,但我又添加了一些东西。

@echo off
rem --Set variable below--
set var=condition

rem --Uncomment below line to display contents of variable--
::echo The variable is %var%

rem --Change condition to desired string below--
ECHO.%var%| FIND /I "condition">Nul && (  
  rem --Occurs if the string is found--
  Echo.Variable is "condition"
  color C
  pause
) || (
  rem --Occurs if the string isn't found--
  Echo.Variable is not "condition"
  color A
  pause
)