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

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

有没有简单的解决方法?


当前回答

对我来说最好的方法是:

call :findInString "HelloWorld" "World"

:findInString
ECHO.%1 | FIND /I %2>Nul && ( 
  Echo.Found
) || (
  Echo.Not found
)

其他回答

为了兼容性和易用性,通常最好使用FIND来执行此操作。

还必须考虑是区分大小写匹配还是不区分大小写匹配。

78点的方法(我相信我指的是paxdiablo的帖子)只会匹配大小写敏感,所以你必须为你想要匹配的每个可能迭代的每个大小写变化单独检查。

)真痛苦!只有3个字母,这意味着要完成9个不同的测试!)

此外,很多时候匹配命令输出、循环中的变量或批处理/CMD中指针变量的值更可取。

由于这些原因,这是一个更好的替代方法:

使用方法:查找[/I] [/V] " character to Match"

[/I](不区分大小写) [/V](不能包含字符)

作为单线:

ECHO.%Variable% | FIND /I "ABC">Nul && ( Echo.Found "ABC" ) || ( Echo.Did not find "ABC" )

多行:

ECHO.%Variable%| FIND /I "ABC">Nul && ( 
  Echo.Found "ABC"
) || (
  Echo.Did not find "ABC"
)

如上所述,这对于变量中不允许字符串替换的东西非常有用:

FOR %A IN (
  "Some long string with Spaces does not contain the expected string"
  oihu AljB
  lojkAbCk
  Something_Else
 "Going to evaluate this entire string for ABC as well!"
) DO (
  ECHO.%~A| FIND /I "ABC">Nul && (
    Echo.Found "ABC" in "%A"
  ) || ( Echo.Did not find "ABC" )
)

Output From a command:

    NLTest | FIND /I "ABC">Nul && ( Echo.Found "ABC" ) || ( Echo.Did not find "ABC" )

As you can see this is the superior way to handle the check for multiple reasons.

我通常是这样做的:

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

我不知道这是不是最好的办法。

对我来说最好的方法是:

call :findInString "HelloWorld" "World"

:findInString
ECHO.%1 | FIND /I %2>Nul && ( 
  Echo.Found
) || (
  Echo.Not found
)

在Var中查找文本,示例:

var_text="demo string test"
Echo.%var_text% | findstr /C:"test">nul && (
    echo "found test" 
    ) || Echo.%var_text% | findstr /C:"String">nul && (
             echo "found String with S uppercase letter" 
    ) || (
             echo "Not Found " 
    )

传说:

& Execute_that和execute_this || Ex: Execute_that IF_FAIL execute this && Ex: Execute_that IF_SUCCESSFUL执行此操作 >nul命令无回显结果 中 /C:使用字符串作为文字搜索字符串

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

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

SET searchString=abcd1234
SET key=cd123

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

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

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