Skip to content

Instantly share code, notes, and snippets.

@DBremen
Created February 8, 2021 17:09
Show Gist options
  • Save DBremen/bb05b068fbe44ff2e457188280dafad8 to your computer and use it in GitHub Desktop.
Save DBremen/bb05b068fbe44ff2e457188280dafad8 to your computer and use it in GitHub Desktop.
PowerShell function to extract text between delimiters
function Get-TextWithin {
<#
.SYNOPSIS
Get the text between two surrounding characters (e.g. brackets, quotes, or custom characters)
.DESCRIPTION
Use RegEx to retrieve the text within enclosing characters.
.PARAMETER Text
The text to retrieve the matches from.
.PARAMETER WithinChar
Single character, indicating the surrounding characters to retrieve the enclosing text for.
If this paramater is used the matching ending character is "guessed" (e.g. '(' = ')')
.PARAMETER StartChar
Single character, indicating the start surrounding characters to retrieve the enclosing text for.
.PARAMETER EndChar
Single character, indicating the end surrounding characters to retrieve the enclosing text for.
.EXAMPLE
# Retrieve all text within single quotes
$s=@'
here is 'some data'
here is "some other data"
this is 'even more data'
'@
Get-TextWithin $s "'"
.EXAMPLE
# Retrieve all text within custom start and end characters
$s=@'
here is /some data\
here is /some other data/
this is /even more data\
'@
Get-TextWithin $s -StartChar / -EndChar \
#>
[CmdletBinding()]
param(
[Parameter(Mandatory,
ValueFromPipeline = $true,
Position = 0)]
$Text,
[Parameter(ParameterSetName = 'Single', Position = 1)]
[char]$WithinChar = '"',
[Parameter(ParameterSetName = 'Double')]
[char]$StartChar,
[Parameter(ParameterSetName = 'Double')]
[char]$EndChar
)
$htPairs = @{
'(' = ')'
'[' = ']'
'{' = '}'
'<' = '>'
}
if ($PSBoundParameters.ContainsKey('WithinChar')) {
$StartChar = $EndChar = $WithinChar
if ($htPairs.ContainsKey([string]$WithinChar)) {
$EndChar = $htPairs[[string]$WithinChar]
}
}
$pattern = @"
(?<=\$StartChar).+?(?=\$EndChar)
"@
[regex]::Matches($Text, $pattern).Value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment