Batch file: Find if substring is in string (not in a file)

前端 未结 10 2142
深忆病人
深忆病人 2020-11-22 14:14

In a batch file, I have a string abcdefg. I want to check if bcd is in the string.

Unfortunately it seems all of the solutions I\'m find

10条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 14:47

    Yes, you can use substitutions and check against the original string:

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

    The %str1:bcd=% bit will replace a bcd in str1 with an empty string, making it different from the original.

    If the original didn't contain a bcd string in it, the modified version will be identical.

    Testing with the following script will show it in action:

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

    And the results of various runs:

    c:\testarea> testprog hello
    
    c:\testarea> testprog abcdef
    It contains bcd
    
    c:\testarea> testprog bcd
    It contains bcd
    

    A couple of notes:

    • The if statement is the meat of this solution, everything else is support stuff.
    • The x before the two sides of the equality is to ensure that the string bcd works okay. It also protects against certain "improper" starting characters.

提交回复
热议问题