Home > Software engineering >  Count equal Regex matches
Count equal Regex matches

Time:04-03

I'm currently looking for a way to count equal regex matches and output them in a table or something similar.

My regex looks like this:

$regex = "\A[[]{1}[0-9]{2}[.]{1}[0-9]{2}[.]{1}[0-9]{2}[,]{1}\s[0-9]{2}[:]{1}"

My Powershell code looks like this at the moment and outputs just all the matches the script finds.

((Select-String $content -Pattern $regex -AllMatches).Matches).value

The output the script gives me looks like this (shortened):

[02.12.21, 11:
[02.12.21, 11:
[02.12.21, 11:
[02.12.21, 13:
[02.12.21, 13:
[02.12.21, 13:
[02.12.21, 13:
[02.12.21, 13:
[02.12.21, 13:
[02.12.21, 13:

I would like to output something similar like this:

[02.12.21, 11: (3 times)
[02.12.21, 13: (7 times)

Can someone help me out?

Thanks in advance!

CodePudding user response:

As noted in comments, you can use Group-Object:

$matchValues = @(
    '[02.12.21, 11:'
    '[02.12.21, 11:'
    '[02.12.21, 11:'
    '[02.12.21, 13:'
    '[02.12.21, 13:'
    '[02.12.21, 13:'
    '[02.12.21, 13:'
    '[02.12.21, 13:'
    '[02.12.21, 13:'
    '[02.12.21, 13:'
)

$matchValues | Group-Object | ForEach-Object { '{0} ({1} times)' -f $_.Name, $_.Count }

Output:

[02.12.21, 11: (3 times)
[02.12.21, 13: (7 times)

Each group object's Name property contains the unique value, while its Count property gives you the number of instances of this value.

Finally you can use the format operator -f to produce the desired output.

  • Related