Split a string without separators in PowerShell Split a string without separators in PowerShell powershell powershell

Split a string without separators in PowerShell


You actually can split the string like this if you use a regex.

$arr = $string -split "(..)" -ne ""

The . matches any single character. We then need to filter the array to remove empty values which is where the -ne "" comes in (Thanks mklement0 for the suggestion to replace | ? {$_}).

In action:

C:\Users\Paarth> $string = "160519"C:\Users\Paarth> $arr = $string -split "(..)" -ne ""C:\Users\Paarth> $arr160519C:\Users\Paarth>


If you don't have a delimiter, you can't usefully use -split. Instead you'll have to use something like:

$d = '160519'$a, $b, $c = $d.SubString(0, 2), $d.SubString(2, 2), $d.SubString(4, 2)# (That is like doing:$a = $d.SubString(0, 2)$b = $d.SubString(2, 2)$c = $d.SubString(4, 2)# but doing all three in one go )

Stop here, this is all you need. :-)


Aside: you can index multiple characters out of a string, but they come out as individual characters and each need joining back up into strings again, so it's not neater and not clearer:

$d = '160519'$a, $b, $c = ($d[0..1] -join ''), ($d[2..3] -join ''), ($d[4..5] -join '')

[Edit: I guess, if you really care, you can force -split to work for you, since you can describe two numbers with a regular expression. The problem with doing that is you normally split based on finding a delimiter, throwing the delimiter away, and keeping the rest. If you want to keep the delimiter you can do it with regex groups, but -split will output empty space where it thinks the content should be, so it takes an ugly workaround to make it work:

# split based on a regular expression describing two digits \d\d# capture the digits in a group (\d\d)# Filter the output through Where-Object   |?# Only the numbers will pass, the empty space won't$a, $b, $c = $d -split '(\d\d)' |? {$_}

Or a more standard use of regular expressions with the .Net [Regex] library:

$a, $b, $c = [Regex]::Matches($d, '\d\d') | Select -ExpandProperty Value

or in PowerShell

$d -match '(\d\d)(\d\d)(\d\d)'$a, $b, $c = $matches[1,2,3]# hey, this one's pretty nice.

]


try this

$text="160519"$var0, $var1, $var2, $var3= $text -split "(\d{2})(\d{2})(\d{2})"$var1$var2$var3