26

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

43

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

([regex]::Matches($a, "<= goes here /" )).count
Sign up to request clarification or add additional context in comments.

5 Comments

This doesn't work if the string you are trying to match is only one character long.
What do you do with special characters? If your search string contains ^\|( etc they will have to be escaped.
@N-ate use single quotes and escape using \ : '\^\\\|' to match ^\|
@Backwards_Dave It works fine for me with one character, both for the content of $a and the match. (PS v5.1)
To workaround potential escape issue use: ([regex]::Matches($a, [regex]::Escape("<= goes here /" ))).count
9

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

Comments

8

Using regex:

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

Comments

7

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

Comments

4

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

Comments

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.

Comments

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

Comments

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}
}

Comments

1

Not the best solution but practical:

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

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.