如何以正确的方式(数组)保存字符之间有空格的行? [英] How can I save lines with spaces between characters in the right way (Array)?

查看:450
本文介绍了如何以正确的方式(数组)保存字符之间有空格的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两行示例:


Bob                     02 02 10 80   Enquiries            
Martin      Corp        02 02 10 80   Langar               

请注意,第一行在鲍勃"之后没有任何信息,因此只有空格.

Note, that the first line doesn't have an information after "Bob", so just spaces.

所以我的代码是:

$account_name = $inputFileContent[$i].Split(" ",[System.StringSplitOptions]::RemoveEmptyEntries)

我的输出数组应该像这样:

My output-array should be like:

$account_name =
Bob
(Empty Line)
02
02
10
80
Enquiries

有没有一种方法可以更改代码,因此将其以这种格式保存在数组中?

Is there a way to change the code, so I have it saved in a array in that format?

推荐答案

一种可能是使用正则表达式:

One possibility is to use regular expressions:

Get-Content "data.txt" | ForEach-Object {
    $_ -match "^([a-z]+) +(\w*) +((?:\d{2} ){3}\d{2}) +(\w+)$" | Out-Null

    $account_name = 1..4 | ForEach-Object {$matches[$_]}
}

这会将$account_name设置为:

Bob

02 02 10 80
Enquiries

或:

Martin
Corp
02 02 10 80
Langar

当然,每次$account_name都会被覆盖,因此可以在循环到下一行之前使用它,或者将每组项目添加到数组中.

Of course, $account_name is over-written each time, so either use it before looping around to the next line, or add each set of items to an array.

注意:我假设您实际上希望将代码"作为单个项目使用(例如,"02 02 10 80"),但是如果没有,则可以调整模式以提取单个项目

Note: I assumed you actually wanted the 'code' as a single item (e.g. '02 02 10 80'), but if not, the pattern can be adjusted to pull out the individual items.

这篇关于如何以正确的方式(数组)保存字符之间有空格的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆