For more information regarding the security incident at F5, the actions we are taking to address it, and our ongoing efforts to protect our customers, click here.

Forum Discussion

uni's avatar
uni
Icon for Altocumulus rankAltocumulus
Aug 22, 2007

Test for characters in a string

I want to test whether any of a set of characters exists within a string. I used the code below, but wonder if anyone can suggest a more efficient (and more elegant) method:

 

string match "*\[XYZ\]*" $var

2 Replies

  • hoolio's avatar
    hoolio
    Icon for Cirrostratus rankCirrostratus
    I think scan would be faster and work assuming you can use a character class to define what you want to match.

     

     

    Click here

     

     

    [chars]

     

    The input substring consists of one or more characters in chars. The matching string is stored in the variable. If the first character between the brackets is a ] then it is treated as part of chars rather than the closing bracket for the set. If chars contains a sequence of the form a-b then any character between a and b (inclusive) will match. If the first or last character between the brackets is a -, then it is treated as part of chars rather than indicating a range.

     

     

     

     

    Aaron
  • Another option is to use the switch statement. So if you just want to see if "X", "Y", or "Z" are in a string, this would do the trick:

    switch -glob $var {
      "*A*" -
      "*B*" -
      "*C*" {
         match found
      }
      default {
         no match found
      }
    }

    This will perform a bit faster than a comparable regular expression or if/elseif statements.

    -Joe