chuacw
chuacw

Reputation: 1863

Testing for string in PowerShell

I am a PowerShell newbie and I have a string in $line.

How do I test that $line has the word "Bat", such that it succeeds for the string "Bat man", but fails for "Batman"?

In other words, I want to test for a standalone word, not a string sequence that is part of a word.

Upvotes: 3

Views: 292

Answers (1)

Akim
Akim

Reputation: 8679

Use word boundary a metacharacter for regex. The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary".

#True
"Bat" -match "\bBat\b"

#also True
"Bat man" -match "\bBat\b"

#False
"Batman" -match "\bBat\b"

#False
"another Batman" -match "\bBat\b"

#True
"another Bat man" -match "\bBat\b"

Upvotes: 3

Related Questions