Check if String contains "*" (Character rather than wildcard)

This topic contains 3 replies, has 3 voices, and was last updated by  Mark Prior 5 months, 3 weeks ago.

  • Author
    Posts
  • #69537

    Mark Prior
    Participant

    hopefully a quick one, how do i check if the String $from contains the character * rather than it searching for everything ?

    ideally i want the result from the below to produce the ELSE output

    
    $From = "ikea"
    $subject = "are*"
    
    
    if ($from -like "*")
    
    {
    
    write-output "String contains the * character"
    
    
    }
    
    else {
    
    Write-Output "String does not contain the * Character"
    
    }
    
    

    Then alternately produce the first match write-output "String contains the * character" from below

    
    $From = "ikea*"
    $subject = "are*"
    
    
    if ($from -like "*")
    
    {
    
    write-output "String contains the * character"
    
    
    }
    
    else {
    
    Write-Output "String does not contain the * Character"
    
    }
    
    
  • #69546

    Daniel Krebs
    Moderator

    Hi Mark,

    You can use the -match operator if you escape the * with a backslash or the Contains() method of the String object.

    Example:

    $From = 'ikea'
    $subject = 'are*'
    
    
    if ($from -match '\*')
    {
        write-output '-match     : String contains the * character'
    }
    else {
        Write-Output '-match     : String does not contain the * Character'
    }
    
    if ($from.Contains('*'))
    {
        write-output '.Contains(): String contains the * character'
    }
    else {
        Write-Output '.Contains(): String does not contain the * Character'
    }
    

    I hope above helps.

    Regards,
    Daniel

  • #69547

    Maurice
    Participant

    You can use the match operator to match the string on a regular expression:

    $From = "ikea*"
    $subject = "are*"
    
    if ($from -match "\*")
    {
      write-output "String contains the * character"
    }
    else 
    {
      Write-Output "String does not contain the * Character"
    }
    
  • #69549

    Mark Prior
    Participant

    Thanks Both

You must be logged in to reply to this topic.