String 将一个变量与批处理中另一个变量的部分匹配

String 将一个变量与批处理中另一个变量的部分匹配,string,batch-file,match,String,Batch File,Match,我想将一个变量与批处理中另一个变量的部分内容相匹配。下面是一些我想做的伪代码 set h= Hello-World set f= This is a Hello-World test if %h% matches any string of text in %f% goto done :done echo it matched 有人知道我是如何做到这一点的吗?基于,您可以使用命令使用/C开关来比较字符串(根据链接答案进行修改,这样您就不必使用单独的批处理文件来比较字符串): 如果满足以下条件

我想将一个变量与批处理中另一个变量的部分内容相匹配。下面是一些我想做的伪代码

set h= Hello-World
set f= This is a Hello-World test

if %h% matches any string of text in %f% goto done
:done
echo it matched
有人知道我是如何做到这一点的吗?

基于,您可以使用命令使用
/C
开关来比较字符串(根据链接答案进行修改,这样您就不必使用单独的批处理文件来比较字符串):


如果满足以下条件:

  • 搜索不区分大小写
  • 搜索字符串不包含
    =
  • 搜索字符串不包含
然后您可以使用:

@echo off
setlocal enableDelayedExpansion
set h=Hello-World
set f=This is a Hello-World test
if "!f:*%h%=!" neq "!f!" (
  echo it matched
) else (
  echo it did not match
)
搜索词前面的
*
仅用于允许搜索词以
*
开头

可能还有一些涉及引号和特殊字符的其他场景,上述操作可能会失败。我认为应注意以下问题,但最初的限制仍然适用:

@echo off
setlocal enableDelayedExpansion
set h=Hello-World
set f=This is a Hello-World test
for /f delims^=^ eol^= %%S in ("!h!") do if "!f:*%%S=!" neq "!f!" (
  echo it matched
) else (
  echo it did not match
)
还有一种方法:

@echo off
set "h=Hello-World"
set "f=This is a Hello-World test"
call set "a=%%f:%h%=%%"
if not "%a%"=="%f%" goto :done
pause
exit /b
:done
echo it matched
pause

注意-由于在响应中没有明确提及,空格在
SET
string语句中很重要,因此您在变量中设置的值包括前导空格(和任何尾随空格)。令人困惑的是,这也适用于变量名(SET h=something`will SET”
h
“not”
h
)。使用
设置“var=string”
语法可以克服尾随空格的问题。
@echo off
set "h=Hello-World"
set "f=This is a Hello-World test"
call set "a=%%f:%h%=%%"
if not "%a%"=="%f%" goto :done
pause
exit /b
:done
echo it matched
pause