将字符串分成两个数组

时间:2019-04-01 16:03:44

标签: powershell

我有一个像下面这样的字符串

abc-ijk-90-hortons-899-mnb-8037-POI-AS-QWE-ZXC-TYUIOP-KEW-197.127.255.0/23
abc-ijk-90-hortons-975-mnb-8024-POI-AS-QWE-ZXC-TYUIOP-KUYW-198.157.150.0/23
abc-ijk-90-hortons-356-mnb-8022-POI-AS-QWE-ZXC-TYUIOP-JHT-199.127.132.0/23

我想将字符串分成

c1= {8037,8024,8022}
c2= {POI-AS-QWE-ZXC-TYUIOP-KEW-197.127.255.0/23,POI-AS-QWE-ZXC-TYUIOP-KUYW-198.157.150.0/23,POI-AS-QWE-ZXC-TYUIOP-JHT-199.127.132.0/23}

c3应该显示如下

Number  Name
8037    POI-AS-QWE-ZXC-TYUIOP-KEW-197.127.255.0/23
8024    POI-AS-QWE-ZXC-TYUIOP-KUYW-198.157.150.0/23
8022    POI-AS-QWE-ZXC-TYUIOP-JHT-199.127.132.0/23

3 个答案:

答案 0 :(得分:2)

尝试一下:

$Yourstring=@"
abc-ijk-90-hortons-899-mnb-8037-POI-AS-QWE-ZXC-TYUIOP-KEW-197.127.255.0/23
abc-ijk-90-hortons-975-mnb-8024-POI-AS-QWE-ZXC-TYUIOP-KUYW-198.157.150.0/23
abc-ijk-90-hortons-356-mnb-8022-POI-AS-QWE-ZXC-TYUIOP-JHT-199.127.132.0/23
"@

$C3=@()

$Yourstring -split "`n" | %{

$marray=$_ -split '-'
$C3+=[pscustomobject]@{Number=$marray[6];Name=$marray[7..($marray.Count-1)] -join '-'}

}

$C1=$C3.Number
$C2=$C3.Name

答案 1 :(得分:1)

如果您知道所需的号码始终在同一位置,则可以尝试以下操作:

$string = 'abc-ijk-90-hortons-899-mnb-8037-POI-AS-QWE-ZXC-TYUIOP-KEW-197.127.255.0/23'

# Split on dash
$array = $string.Split('-')

# build new array from position 7 on
$name = @()
for($i = 7; $i -lt $array.count; $i++){
    $name += $array[$i]
}

# create PS object with the Number from position 6 and the remainder rejoined together.
[pscustomobject]@{Number = $array[6]; Name = $name -join('-')}

答案 2 :(得分:1)

  • -处拆分字符串的行,但将拆分限制为8次,
    这样一来POI-...就一直保持到行尾
  • 然后选择基于零的索引[6,7]填充到vars $ Number,$ Name
  • 构建这两个变量的[PSCustomObject]。
  • 最终从$ c3的属性中构建$ c1,$ c2

$string = @"
abc-ijk-90-hortons-899-mnb-8037-POI-AS-QWE-ZXC-TYUIOP-KEW-197.127.255.0/23
abc-ijk-90-hortons-975-mnb-8024-POI-AS-QWE-ZXC-TYUIOP-KUYW-198.157.150.0/23
abc-ijk-90-hortons-356-mnb-8022-POI-AS-QWE-ZXC-TYUIOP-JHT-199.127.132.0/23
"@ -split '\r?\n'

$c3 = foreach ($line in $string){
    $Number,$Name= ($line -split '-',8)[6,7]
    [PSCustomObject]@{
        Number = $Number
        Name   = $Name
    }
}
# it's not quite clear what type you expect $c1,$c2 to be.
# a simple joined string
$c1 = '{'+($c3.Number -join ',')+'}'
$c2 = '{'+($c3.Name   -join ',')+'}'

$c1;$c2;$c3

示例输出:

{8037,8024,8022}
{POI-AS-QWE-ZXC-TYUIOP-KEW-197.127.255.0/23,POI-AS-QWE-ZXC-TYUIOP-KUYW-198.157.150.0/23,POI-AS-QWE-ZXC-TYUIOP-JHT-199.127.132.0/23}

Number Name
------ ----
8037   POI-AS-QWE-ZXC-TYUIOP-KEW-197.127.255.0/23
8024   POI-AS-QWE-ZXC-TYUIOP-KUYW-198.157.150.0/23
8022   POI-AS-QWE-ZXC-TYUIOP-JHT-199.127.132.0/23