16

How would you go about counting the number of strings within a string using Powershell?

For example:

$a = "blah test <= goes here / blah test <= goes here / blah blah"

I want to count how many times <= goes here / appears in the above.

9 Answers 9

38

another way (similar to @mjolinor way) in one line:

([regex]::Matches($a, "<= goes here /" )).count
5
  • 1
    This doesn't work if the string you are trying to match is only one character long. Jun 29, 2017 at 6:05
  • 1
    What do you do with special characters? If your search string contains ^\|( etc they will have to be escaped.
    – N-ate
    Nov 21, 2017 at 18:46
  • @N-ate use single quotes and escape using \ : '\^\\\|' to match ^\|
    – Farway
    Apr 2, 2019 at 17:36
  • @Backwards_Dave It works fine for me with one character, both for the content of $a and the match. (PS v5.1)
    – Farway
    Apr 5, 2019 at 13:47
  • 1
    To workaround potential escape issue use: ([regex]::Matches($a, [regex]::Escape("<= goes here /" ))).count
    – Stoinov
    Apr 7, 2021 at 13:44
7

I had a string with a bunch of pipes in it. I wanted to know how many there were, so I used this to get it. Just another way :)

$ExampleVar = "one|two|three|four|fivefive|six|seven";
$Occurrences = $ExampleVar.Split("|").GetUpperBound(0);
Write-Output "I've found $Occurrences pipe(s) in your string, sir!";
  • Marcus
6

Using regex:

$a = "blah test <= goes here / blah test <= goes here / blah blah"
[regex]$regex = '<= goes here /'
$regex.matches($a).count
2
3

You can use the [.NET String.Split][1] method overload that takes an array of string objects and then count how many splits you get.

($a.Split([string[]]@('<= goes here /'),[StringSplitOptions]"None")).Count - 1

Note that you have to cast the string your searching for to a string array to make sure you get the correct Split overload and then subtract 1 from the result because split will return all the strings that surround your search string. Also important is the "None" option that will cause Split to return null strings in the array (that you can count) if your search string returns at the start or end.

3

Yet another alternative one liner: (Select-String "_" -InputObject $a -AllMatches).Matches.Count

2

I'm surprised no one mentioned the -split operator.

For a case-sensitive match, opt for the -cSplit operator as -split/-iSplit are both case-insensitive.

PS Y:\Power> $a = "blah test <= goes here / blah test <= goes here / blah blah"

# $a -cSplit <Delimiter>[,<Max-substrings>[,"<Options>"]]
# Default is RegexMatch (makes no difference here):
PS Y:\Power> ($a -cSplit '<= goes here /').Count - 1
2

# Using 'SimpleMatch' (the 0 means return no limit or return all)
PS Y:\Power> ($a -cSplit '<= goes here/',0,'simplematch').Count - 1
2
2

another solution with Select-String

$a = "blah test <= goes here / blah test <= goes here / blah blah"

($a | Select-String -Pattern "<= goes here /" -AllMatches).Matches.Count

Select-String docs:

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/select-string

1

Just to expand on BeastianSTI' excellent answer:

Finding the maximum number of separators used in a line of a file (line unknown at run time):

$myNewCount = 0
foreach ($line in [System.IO.File]::ReadLines("Filename")){
    $fields = $line.Split("*").GetUpperBound(0);
    If ($fields -gt $myNewCount)
    {$myNewCount = $fields}
}
1

Not the best solution but practical:

$a.Replace("<= goes here /","♀").Split("♀").Count

Make sure that your text does not contain "♀" character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.