Windows Batch check if variable starts with, ends with and contains a specific string

后端 未结 3 796
天涯浪人
天涯浪人 2020-12-17 22:17

I\'m trying to check if a variable in a batch file starts with \" contains BETA somewhere and ends with \").

Is it possible? A

3条回答
  •  温柔的废话
    2020-12-17 23:23

    @echo off
    setlocal EnableDelayedExpansion
    set quote="
    set variable="This must be true: BETA")
    echo Variable=!variable!
    if "!variable:~0,1!" equ "!quote!" (
       rem Start with "
       if "!variable:BETA=!" neq "!variable!" (
          rem Contains BETA
          if "!variable:~-2!" equ "!quote!^)" (
             echo TRUE: it start with " contains BETA and ends with "^)
          ) else (
             echo FALSE, it does not ends with "^)
          )
       ) else (
          echo FALSE, it does not contain BETA
       )
    ) else (
       echo FALSE, it does not start with "
    )
    

    Output:

    Variable="This must be true: BETA")
    TRUE: it start with " contains BETA and ends with ")
    
    • The way to deal with unbalanced quotes (and with other special Batch characters, indeed) is to use Delayed Expansion: this way the quotes and special characters don't appear in the command line being parsed.

    • Remember to escape with ^ any right parentheses that are not closing parentheses of command blocks.

    • An easy way to check if a variable contain a given string is try to eliminate the string from variable value: if the result is different to the original value, then the variable contain the string.

    Antonio

提交回复
热议问题