Finding the number of text matches in a String

So today I needed to find out how many times a piece of text was found inside a string. I was given a large page of text and needed to find out how many times a word or phrase appeared on that page.

# All of the text I’ve placed in a ‘here string’
$text= @”
blah, blah, blah, test, test, test, blah, blah, blah
“@

# And let’s look for the word “blah”
([regex]::Matches($text, “blah” )).count

The result will be “6”.

I should point out that using .NET Regex by default is Case-Sensitive…so if I change the here string by adding a “BLAH” in caps, and re-run it, I’ll just get back the result of 6 still because “BLAH” is not the same as “blah”. To fix this, we’ll add a few characters to the start of our search string which instructs PowerShell to ignore the case, or in other words make this a Case-Insensitive match.

# All of the text I’ve placed in a ‘here string’
$text= @”
blah, blah, blah, test, test, test, blah, blah, blah, BLAH
“@

# And let’s look for the word “blah”
([regex]::Matches($text, “(?i)blah” )).count

The result will now be “7”.

 

Optionally, you might want to simply find if the word “blah” occurs inside that string. We could use the following:

$text -match ‘blah’

The result would be returned as “True”. Using this PowerShell method by the way, is Case-Insensitive by default.

 
Comments

No comments yet.

Leave a Reply