SiMe
SiMe

Reputation: 11

Powershell search for string in array with special characters

Powershell question: I have an array $myArray that contains the following values:

$myArray[0]:smith,server1,1/1/2015 10:00:00
$myArray[1]:smithpeter,server1,1/1/2015 10:00:00

I'd like to find out if $myArray already contains the value "smith" anywhere, but I do not want to include "smith*" (e.g. smithpeter) in the results.

If I try

[regex]$regex="smith"
$myArray -match $regex

it returns both records (smith and smithpeter) --> correct, but not what I want.

If I try

[regex]$regex="smith,"
$myArray -match $regex

I am getting no results.

I can't find any proper answers online. I believe the fact that I have a comma (",") in the string seems to be causing some issues with the query.

Thanks for any input.

Upvotes: 1

Views: 1183

Answers (2)

A. Eakins
A. Eakins

Reputation: 313

In addition to word-boundary, you can use the caret "^" to indicate the start position of the expression and the dollar sign "$" to indicate the end.

[regex]$regex="^smith$"

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627101

All you need is to add a word boundary \b round smith to match it as a whole word.

[regex]$regex="\bsmith\b"

Also see What is a word boundary in regexes? SO post for more details.

Upvotes: 3

Related Questions