-
Notifications
You must be signed in to change notification settings - Fork 8.1k
Description
-match is a handy regex-matching operator, but it is limited to finding (at most) one match, as afterwards reflected in the automatic $Matches variable (with a scalar LHS) or directly returned (with an array-valued LHS).
Additionally, the ability to retrieve the matching part of the input and any capture-group values is lost with an array-valued LHS, because $Matches is then not populated.
In order to find all matches of a given regex, you currently have two options:
-
Pipe to
Select-String -AllMatches, but that is inefficient for matching (collections of) strings already in memory. -
Use .NET directly, via the
[regex]::Matches()method, but that makes for an awkward transition from the PowerShell-native-matchoperator.
Therefore, a -matchall (-imatchall, -cmatchall) operator could be introduced, as a PowerShell-friendly wrapper for the [regex]::Matches() method
# WISHFUL THINKING
# Scalar LHS; returns a collection of 2 matches
'foo' -matchall 'o'
# Array LHS; returns 2 collections of 2 matches each
'foo', 'baa' -matchall 'o|a'could be the equivalent of:
# Scalar LHS
[regex]::matches('foo', 'o')
# Array LHS
[regex]::matches('foo', 'o|a'), [regex]::matches('baa', 'o|a')That is, the output would be either a single [System.Text.RegularExpressions.MatchCollection] instance, or an array of them, each of which contains one [System.Text.RegularExpressions.Match] instance per match.
A [System.Text.RegularExpressions.Match] instance stringifies to the matching part of the input string, if any, and contains capture-group values as well as additional metadata about the match.
In essence, this is also what you get when you access the .Matches property of the [Microsoft.PowerShell.Commands.MatchInfo] instances returned by Select-String -AllMatches (though in the case of Select-String an [object[]] array of [System.Text.RegularExpressions.Match] is returned instead of a [System.Text.RegularExpressions.MatchCollection] instance).
Environment data
Written as of:
PowerShell Core 6.1.0