Skip to content

Instantly share code, notes, and snippets.

@scriptingstudio
Last active April 6, 2025 10:30
Show Gist options
  • Select an option

  • Save scriptingstudio/7ad6c55590c384914854f39537755b2e to your computer and use it in GitHub Desktop.

Select an option

Save scriptingstudio/7ad6c55590c384914854f39537755b2e to your computer and use it in GitHub Desktop.
Regex at work. Strange way to slice strings
function Slice-String ([string]$string, [int]$length, [int[]]$part) {
if ($length -gt 1) {
if ($part.count) {
($string -split "(?<=.)(?=(?:.{$length})+$)")[$part]
} else {
$string -split "(?<=.)(?=(?:.{$length})+$)"
}
} else {$string}
}
function Slice-String {
[CmdletBinding()]
param (
[parameter(ValueFromPipeline)]
[string]$string,
[int]$length, [int[]]$part
)
process {
if ($length -gt 1) {
if ($part.count) {
($string -split "(.{$length})").where{$_}[$part]
} else {
($string -split "(.{$length})").where{$_}
}
} else {$string}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment