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.
another way (similar to @mjolinor way) in one line:
([regex]::Matches($a, "<= goes here /" )).count
$a
and the match. (PS v5.1)
([regex]::Matches($a, [regex]::Escape("<= goes here /" ))).count
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!";
Using regex:
$a = "blah test <= goes here / blah test <= goes here / blah blah"
[regex]$regex = '<= goes here /'
$regex.matches($a).count
2
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.
Yet another alternative one liner: (Select-String "_" -InputObject $a -AllMatches).Matches.Count
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
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
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}
}
Not the best solution but practical:
$a.Replace("<= goes here /","♀").Split("♀").Count
Make sure that your text does not contain "♀" character.