Skip to content

Introduce a -matchall operator that finds *all* regex matches, to complement -match #7867

@mklement0

Description

@mklement0

-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 -match operator.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Enhancementthe issue is more of a feature request than a bugKeepOpenThe bot will ignore these and not auto-closeWG-Languageparser, language semantics

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions