Skip to content

Instantly share code, notes, and snippets.

@dotps1
Last active January 5, 2024 08:07
Show Gist options
  • Save dotps1/b4ae09ea6673d03f40faf0dd348b74e6 to your computer and use it in GitHub Desktop.
Save dotps1/b4ae09ea6673d03f40faf0dd348b74e6 to your computer and use it in GitHub Desktop.
Finds the nth index of a char in a string.
<#
.SYNOPSIS
Finds the nth index of a char in a string.
.DESCRIPTION
Finds the nth index of a char in a string, returns -1 if the char does not exist, or if nth is out of range.
.INPUTS
System.Char.
System.String.
System.Int.
.OUTPUTS
System.Int.
.PARAMETER Target
The string to evaluate.
.PARAMETER Value
The char to locate.
.PARAMETER Nth
the occurance of the char to find.
.EXAMPLE
PS C:\> Find-NthIndexOf -Target "CN=me,OU=Users,DC=domain,DC=org" -Value "=" -Nth 2
8
.EXAMPLE
PS C:\> ($dn = "CN=me,OU=Users,DC=domain,DC=org").SubString((Find-NthIndexOf -Target $dn -Value "=" -Nth 2) - 2)
OU=Users,DC=domain,DC=org
.NOTES
Returns -1 if the char does not exist, or if nth is out of range.
.LINK
http://stackoverflow.com/questions/186653/c-sharp-indexof-the-nth-occurrence-of-a-string
.LINK
https://dotps1.github.io
#>
Function Find-NthIndexOf {
[CmdletBinding()]
[OutputType(
[Int]
)]
Param (
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true
)]
[String[]]
$Target,
[Parameter(
Mandatory = $true,
ValueFromPipelineByPropertyName = $true
)]
[Char]
$Value,
[Parameter(
ValueFromPipelineByPropertyName = $true
)]
[Int]
$Nth = 1
)
Process {
foreach ($item in $Target) {
$Value = [Regex]::Escape(
$Value
)
$match = [Regex]::Match(
$item, "(($Value).*?){$Nth}"
)
if ($match.Success) {
Write-Output -InputObject $match.Groups[2].Captures[$Nth - 1].Index
} else {
Write-Output -InputObject -1
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment