Quantcast
Channel: PowerShell General
Viewing all articles
Browse latest Browse all 10624

Checking how may times a substring appears in a string.

$
0
0

Hello All,

I am a big fan of RegEx (always trying to learn something new), and though I would post this tip (by the way how do you post tips on the poweshell tips section?)

If you have a string like this "ACAABBAAZZZAAA"

Normally using Regex if you want to find how may times the letter A appears either on its own or next to it self i.e. A or AA or AAA etc you could type the following to try and get the answer.

"ACAABBAAZZZAAA" - match "A+"

Meaning the letter A one or more times, the thing is by default RegEx is 'eager' meaning it will return the first valid match i.e. it will return A and then end, so you only get a count of 1.

However as above you may want to know how many time the pattern A+ matches through out the whole string, well you can do this

cls
$Matches = $Null
$subject="ACAABBAAZZZAAA"
$resultlist = new-object System.Collections.Specialized.StringCollection
$regex = [regex] 'A+'
$match = $regex.Match($subject)
while ($match.Success) {
    $resultlist.Add($match.Value) | out-null
    $match = $match.NextMatch()
}

$resultlist

This will return the number

A
AA
AA
AAA

I you just want the number of matches then add .count to $resultlist i.e.

cls
$Matches = $Null
$subject="ACAABBAAZZZAAA"
$resultlist = new-object System.Collections.Specialized.StringCollection
$regex = [regex] 'A+'
$match = $regex.Match($subject)
while ($match.Success) {
    $resultlist.Add($match.Value) | out-null
    $match = $match.NextMatch()
}

$resultlist.count

4

The above code is curtsey to RegExBuddy (check out RegExBuddy.com)

This is only a simple example, you may be able to achieve the same thing with select-string (I am newish to PowerShell, so I will leave to the experts here to see if there is a way to achieve the same thing with Select-string or similar).

Hope this helps someone

Ernie

 


Viewing all articles
Browse latest Browse all 10624

Trending Articles