Created
July 3, 2025 14:56
-
-
Save robderickson/4699daba5273df80a0244c5d4e2bf54f to your computer and use it in GitHub Desktop.
Get regex matches in a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Get-StringMatch { | |
<# | |
.SYNOPSIS | |
Get all occurrences in a string matching the provided regex pattern. | |
.PARAMETER String | |
The string you want to check for pattern matches. | |
.PARAMETER Pattern | |
The pattern you want to match in the string | |
.EXAMPLE | |
Get-StringMatch -String 'Hello World' -Pattern 'World' | |
Returns a match collection with a single item matching the pattern 'World'. | |
.EXAMPLE | |
Get-StringMatch -String 'Hello World' -Pattern 'world' -IgnoreCase | |
Returns a match collection with a single item matching the pattern 'world' and ignoring case. | |
.EXAMPLE | |
Get-StringMatch -String 'Hello World' -Pattern 'l' | |
Returns a match collection with three items matching the pattern 'l'. | |
#> | |
[CmdletBinding()] | |
[OutputType([System.Text.RegularExpressions.Match])] | |
param ( | |
[Parameter( | |
Mandatory, | |
ValueFromPipelineByPropertyName | |
)] | |
[string]$String, | |
[Parameter( | |
Mandatory, | |
ValueFromPipelineByPropertyName | |
)] | |
[string]$Pattern, | |
[Parameter( | |
ValueFromPipelineByPropertyName | |
)] | |
[switch]$IgnoreCase | |
) | |
process { | |
if ($IgnoreCase) { | |
[regex]::Matches($String, $Pattern, [System.Text.RegularExpressions.RegexOptions]::IgnoreCase) | |
} else { | |
[regex]::Matches($String, $Pattern) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment