Matching consecutive words in a sentence

Viewed 65

I would like to match a partial sentence against another string.

In the example below I want it to print "True" if it finds Hello then Mich then Brooklyn in the other string. This is how it works in Linux, I don't see anyone doing this in PS. I would like to create a string that has the wildcards in it already to simplify coding.

$Keywords = "Hello.*Mich.*Brooklyn"

Example 1

$Sentence = "Hello I am Michael From Brooklyn New York"
if ($Keywords -Match $Sentence) {
    Write-Host("True")
} else {
   Write-Host("False")
}

Desired output: True

Example 2

# Output should be 'False'
$Sentence = "Hello I am Michael From QUEENS New York"
if ($Keywords -Match $Sentence) {
    Write-Host("True")
} else {
   Write-Host("False")
}

Desired output: False

1 Answers

The left-hand side (LHS) and right-hand side (RHS) of the operator are reversed. The RHS of -match needs to be the regex string. The following will give the desired result.

$Sentence -match $Keywords

If you are comparing a single string against a regex string using -match, True will be returned if there is a match. False is otherwise returned. When the LHS is an array rather than a single string, then the items in the collection that successfully match are returned instead.

Related