Search code examples
powershellpowershell-5.0

Find first occurrence of any one of the array elements in a string - Powershell


The problem is to find the position of the very first occurrence of any of the elements of an array.

$terms = @("#", ";", "$", "|");

$StringToBeSearched = "ABC$DEFG#";

The expected output needs to be: 3, as '$' occurs before any of the other $terms in the $StringToBeSearched variable

Also, the idea is to do it in the least expensive way.


Solution

  • # Define the characters to search for as an array of [char] instances ([char[]])
    # Note the absence of `@(...)`, which is never needed for array literals,
    # and the absence of `;`, which is only needed to place *multiple* statements
    # on the same line.
    [char[]] $terms = '#', ';', '$', '|'
    
    # The string to search trough.
    # Note the use of '...' rather than "...", 
    # to avoid unintended expansion of "$"-prefixed tokens as
    # variable references.
    $StringToBeSearched = 'ABC$DEFG#'
    
    # Use the [string] type's .IndexOfAny() method to find the first 
    # occurrence of any of the characters in the `$terms` array.
    $StringToBeSearched.IndexOfAny($terms)  # -> 3