Home > OS >  Powershell -Match operator only finding first match
Powershell -Match operator only finding first match

Time:07-25

"This is **bold** and this is also **BOLD**,finally this is also **Bold**" -match '\*\*.*?\*\*'

Finds only the first match

$Matches.count

Returns only 1

Doing the same thing with -Replace Finds all matches in the string:

"This is **bold** and this is also **BOLD**,finally this is also **Bold**" -replace '\*\*.*?\*\*', 'Substring'

It matches and replaces all instances:

This is Substring and this is also Substring,finally this is also Substring

How do I get the -Match operator to find all matches and return them as arrays belonging to the $Matches variable? Thanks!

CodePudding user response:

  • The -match operator indeed only finds at most one match in its input, invariably and by design, whereas -replace invariably finds and replaces all matches.

  • As of PowerShell 7.2.x, you need to use the underlying .NET APIs directly in order to find multiple matches, namely the [regex]::Matches() method.

    • GitHub issue #7867 proposes introducing a -matchall operator to provide a PowerShell-native implementation - while the proposal has been green-lit, no one has stepped up to implement it yet.
[regex]::Matches(
  'This is **bold** and this is also **BOLD**,finally this is also **Bold**',
  '\*\*.*?\*\*'
).Value

Note that [regex]::Matches() returns a collection of [System.Text.RegularExpressions.Match] instances, whose .Value property contains the matched text.

  • Related