【问题标题】:How to parse this kind of output in c#如何在c#中解析这种输出
【发布时间】:2018-10-01 07:06:37
【问题描述】:

我有以下格式的输出

Image Name                     PID Services                                    
========================= ======== ============================================
System Idle Process              0 N/A                                         
services.exe                   436 N/A                                         
svchost.exe                    500 BrokerInfrastructure, DcomLaunch, LSM,      
                                   PlugPlay, Power, SystemEventsBroker         
vnetd.exe                    18504 NetBackup Legacy Network Service   

我想将输出存储在这样的数组中:

ar[0]=System Idle Process
ar[1]=0
ar[2]=N/A

我尝试根据空格拆分字符串,但没有成功。任何人都可以建议如何拆分它并在 c# 中获得所需的输出

【问题讨论】:

  • 请发布您的代码并定义“没有成功”
  • @Dave.. 我试图在一个空白的基础上进行拆分,例如 formatedop = Regex.Split(item, @"\s{1}"); formatedop = formatedop.Where(x => !string.IsNullOrEmpty(x)).ToArray();但我没有得到正确的列数
  • 如果图像名称永远不会包含数字,您可以使用:在空格中拆分字符串并遍历所有部分,直到找到数字。也许你可以使用一个正则表达式,它也会在数字上分开。
  • @royalTS..我使用了正则表达式,但我以以下方式获取输出 ar[0]=System ar[1]=Idle ar[2]=Process ar[3]=0 ar[ 4]=不适用
  • 好像你有固定宽度的字段(被填充),你可以根据= 标志定义宽度,然后像这样子串起来?

标签: c# arrays string split string-formatting


【解决方案1】:

看起来你收到的信息有一个固定宽度的输出,所以,你可以使用string.Substring来获取你想要的每次字符串的一部分。

您可以像这样读取输入中的项目:

public static IEnumerable<ProcessItem> GetItemsFromText(string text) {
    var lines = text.Split( new [] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries );
    ProcessItem current = null;
    Console.WriteLine( "Lines found: {0}", lines.Length );
    // skip first 2 lines (header and = signs)
    for (int i = 2; i < lines.Length; i++) {
        var name = lines[i].Substring( 0, 25 ).Trim();
        var pid = lines[i].Substring( 26, 8 ).Trim();
        var services = lines[i].Substring( 35 ).Trim();
        if (!string.IsNullOrWhiteSpace( name ) ) {
            if (current != null) {
                yield return current;
            }
            current = new ProcessItem {
                Name = name,
                Pid = pid,
                Services = services
            };
        } else {
            current.Services += ' ' + services;
        }
    }
    if (current != null) {
        yield return current;
    }
}

此版本还会确认您有多个订单项,并会发回一个自定义类 ProcessItem,如下所示

public class ProcessItem {
    public string Name { get; set; }
    public string Pid { get;set; }
    public string Services { get;set; }
}

您可以在.netfiddle 中找到代码的运行版本

【讨论】:

  • 将数据作为可枚举的对象列表而不是二维数组返回是一个不错的选择,但如果您解释了为什么这是一个好主意,我认为这将是一个更好的答案。
  • @RobinBennett 你说得对,我也许可以通过解释来改进答案,但也许他想要一个数组是有原因的。我猜 OP 可以决定他是否需要更多信息 :)
【解决方案2】:
use substring on the basis of padding 

formatedop[0] = item.Substring(0, 25);
formatedop[1] = item.Substring(25, 10);
formatedop[2] = item.Substring(35, 40);

it will give the result

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多