I saw a challenge to find the occurrences of the sequence 1759 in the larger sequence 11759171759. It was originally presented as a SQL Server based challenge to be solved with TSQL but we can do this just as easily with PowerShell using Select-String
£> $data = ‘11759171759’
£> Select-String -InputObject $data -Pattern ‘1759’ -AllMatches | foreach {$_.Matches.Index}
1
7
Create a variable to hold the big sequence and use that with the –InputObject parameter of Select-String. Supply the pattern to be tested and use –AllMatches to get all matches not just the first which is default. The resultant MatchInfo is piped to foreach-object where the Index of each match is retrieved.
if you want to see the full MatchInfo
£> $m = Select-String -InputObject $data -Pattern ‘1759’ -AllMatches
£> $m.Matches
Groups : {1759}
Success : True
Captures : {1759}
Index : 1
Length : 4
Value : 1759
Groups : {1759}
Success : True
Captures : {1759}
Index : 7
Length : 4
Value : 1759
The indexes are zero based. Add one if you want the position based on a starting index of 1
£> foreach ($match in (Select-String -InputObject $data -Pattern ‘1759’ -AllMatches).Matches){$match.Index + 1}
2
8
Interesting puzzle that gives a good example of using Select-String