PowerTip: Finding Letters in Strings with PowerShell

PowerTip: Finding Letters in Strings with PowerShell

  • Comments 8
  • Likes

Summary: Learn four ways to use Windows PowerShell to find letters in strings.

Hey, Scripting Guy! Question I want to find out if a string contains the letter “m.” The string is stored in the variable $a as shown here:

$a=”northern hairy-nosed wombat”

Hey, Scripting Guy! Answer Here are a variety of ways to accomplish this:

a.  [string]$a.contains(“m”)

b.  $a.contains(“m”)

c.  [regex]::match($a,"m")

d.  ([regex]::match($a,"m")).success

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Hi Ed,

    I usually don't add alternatives to your PowerTips, but this time I'm missing the most obvious expression:

    $a -match 'm' or maybe

    $a -like '*m*'

    And, if I think back of VBScript, there is an "indexof" string member, that we can use:

    $a.IndexOf('m') -ge 0

    Klaus.

  • Hi

    here some variant:

    PS II> [regex]::ismatch($a,"m")

    TRUE

    PS II> Select-String -InputObject $a -Pattern m -Quiet -SimpleMatch

    TRUE

    PS II> $a -replace 'm' -ne $a

    TRUE

  • another variant:

    PS II> $a.ToCharArray() -contains 'm'

    TRUE

    PS II> 'm' in $a.ToCharArray()   #PS3

    TRUE

  • And today has been brought to you by the letter "M".

  • @K_Schulte I am glad you add additional suggestions. I am not posting "edicts" here, but am really wanting to get a conversation started. Everyone who does PowerShell for more than a few months ends up doing things their favorite way. I am hoping to show other ways of doing things, so that we can add an additional tool in our box of tricks. Thank you for sharing.

  • @Walid Toumi Those are great additions. Thank you for sharing.

  • @JRV we quit doing Sesame Script years ago ... :-)

  • @Ed. Then you should be able to use the rest of the alphabet.  

    I thought 'Sesame Script' was more like "Open sesame'" - You know. LIke Ali Baba.