在c#中解析的简单方法

时间:2013-08-30 15:16:54

标签: c# regex

我是regex的新手。我想解析以下数据。我已经提出了一些似乎在sublime上工作的正则表达式,但是当我在visual studio中测试它时它将无法工作。我想知道是否有人可以提供一个简单的示例或指导如何使用正则表达式解析它。它必须非常简单,我必须理解我的错误,所以请事先道歉。

这是我正在处理的数据。

Fri 11:00 - 12:00
                            Max Agents: 1
                            Min Agents: 2
                            Total Calls: 3
                            Answered Calls: 4
                            Abandoned Calls: 5
                            Average Time to Answer (secs): 6
                            Longest Time to Answer (secs): 7
                            Average Time in Call (secs): 8
                            Longest Time in Call (secs): 9
                            Average Time before Abandon (secs): 10
                            Per agent statistics:
                              Agent: 1001
                                From Direct Call:
                                  Total Calls Answered : 11
                                  Average Time in Call (secs) : 12
                                  Longest Time in Call (secs) : 13
                                From Queue:
                                  Total Calls Answered : 2
                                  Average Time in Call (secs) : 14
                                  Longest Time in Call (secs) : 15
                              Agent: 1002
                                From Direct Call:
                                  Total Calls Answered : 1
                                  Average Time in Call (secs) : 16
                                  Longest Time in Call (secs) : 17
                                From Queue:
                                  Total Calls Answered : 2
                                  Average Time in Call (secs) : 18
                                  Longest Time in Call (secs) : 19
                            Queue related statistics:
                              Total calls presented to the queue: 20
                              Calls answered by agents: 21
                              Number of calls in the queue: 22
                              Average time to answer (secs): 23
                              Longest time to answer (secs): 24
                              Number of abandoned calls: 25
                              Average time before abandon (secs): 26
                              Calls forwarded to voice mail: 27
                              Calls answered by voice mail: 28
                              Number of error calls: 29

这是唯一获得代理人的部分:1004部分。

Agent:.(?<agentNum>\d+)\n?((?:[a-z\s]+from.*\n)+\s(?:[a-z\s]+call.*\n)+)?((?:[a-z\s]+from.*\n)+[\n\s]+(?:[a-z\s]+call.*\n)+)?

我正在尝试提取不同属性的数据,例如 总呼叫已接听 平均通话时间

等等。我基本上想要提取这些字段的数据并存储在表格中。

3 个答案:

答案 0 :(得分:2)

只要文本格式正确并且始终以相同的顺序打印出来,我根本不会使用正则表达式,我会逐行进行并用函数解析文本。

class CallCenterActivity
{
    public CallCenterActivity(string callActivity)
    {
        AgentStistics = new List<AgentStatistic>();

        using(var reader = new StringReader(callActivity))
        {
             ActivityDate = ParseActivityDate(reader.ReadLine());
             MaxAgents = ExtractInt(reader);
             MinAgents = ExtractInt(reader);
             //(Snip)
             AvarageTimeBeforeAbandon = ExtractInt(reader);

             if(reader.ReadLine().Trim().Equals("Per agent statistics:") == false)
                 throw new InvalidDataException("We where not on the line we expected to be for \"Per Agent statistics:\"");

             string currentLine;
             //This loops till we break out of the agent section
             while((currentLine = reader.ReadLine()).Trim().Equals("Queue related statistics:") == false)
             {
                  var agent = new AgentStatistic();
                  agent.AgentId = ExtractInt(reader);
                  agent.DirectCallsAnswered = ExtractInt(reader);
                  //(snip)
                  agent.QueueLongestTimeInCall = ExtractInt(reader);

                  AgentStistics.Add(agent);
             }

             TotalCallsPresentedToQueue = ExtractInt(reader);
             //(Snip)
             CallsAnsweredByVoiceMail = ExtractInt(reader);
        }

    }

    //These parser methods are small and kept static so you could easily write unit tests against each parser.
    private static DateTime ParseActivityDate(string activityDateLine)
    {
        throw new NotImplmentedException("Here you would turn your \"Fri 11:00 - 12:00\" in to a DateTime");
    }

    //ParseInt and ExtractInt are separated to ease Unit Testing.
    private static int ParseInt(string line)
    {
        var split = line.Split(':')
        return Int32.Parse(split[1]);
    }

    private static int ExtractInt(StringReader reader)
    {
        return ParseInt(reader.ReadLine());
    }

    public DateTime ActivityDate {get;set;}
    public int MaxAgents {get;set;}
    public int MinAgents {get;set;}
    public int TotalCalls {get;set;}
    public int AnsweredCalls {get;set;}
    public int AbandonedCalls {get;set;}
    public int AvarageTimeToAnswer {get;set;}
    public int LongestTimeToAnswer {get;set;}
    public int AvarageTimeBeforeAbandon {get;set;}
    public List<AgentStatistic> AgentStistics {get; private set;}
    public int TotalCallsPresentedToQueue {get;set;}
    public int CallsAnsweredByAgents {get;set;}
    public int NumberOfCallsInTheQueue {get;set;}
    public int AvarageTimeToAnswerQueue {get;set;}
    public int LongestTimeToAnswerQueue {get;set;}
    public int NumberOfAbandondCalls {get;set;}
    public int AvarageTimeBeforeAbandon {get;set;}
    public int CallsForwaredToVoiceMail {get;set;}
    public int CallsAnsweredByVoiceMail {get;set;}
}

class AgentStatistic
{
    public int AgentId {get;set;}
    public int DirectCallsAnswered {get;set;}
    public int DirectCallsAverageTimeInCall {get;set;}
    public int DirectCallsLongestTimeInCall {get;set;}
    public int QueueAnswered {get;set;}
    public int QueueAverageTimeInCall {get;set;}
    public int QueueLongestTimeInCall {get;set;}
}

答案 1 :(得分:0)

不确定您要做什么,但这里是使用Regex解析字符串部分的方法。

Regex ex = new Regex("[0-9]*"); //generic regular expression -- look for numbers
Match match = ex.Match(searchString, startAtIndex);
while(match.Success)
{
    string currentMatch = match.Value;

     //do something


    match = match.NextMatch()
 }

答案 2 :(得分:0)

你正在使用正则表达式中的.,我建议你避免使用它。相反,通过匹配 [任何 感兴趣的的内容,匹配您不感兴趣的大量字符组合。在这种情况下,你想要数字,对吗?

我会这样做(\D,资本D表示[任何不是数字的东西]):

Agent:\s+(?<AgentNum>\d+)(?:\D+)(?<DirectTotal>\d+)(?:\D+)(?<DirectAvg>\d+)(?:\D+)(?<DirectLongest>\d+)(?:\D+)(?<QueueTotal>\d+)(?:\D+)(?<QueueAvg>\d+)(?:\D+)(?<QueueLongest>\d+)

我假设数据集的格式总是像你的例子一样,行顺序从未改变,数字没有被省略(而是设置为0)。

我没有C#或其他任何东西来测试我是否使用了(?<NameSubgroup>matchPattern)正确而且我不熟悉C#必须迭代匹配并提取命名子组的方法,但这应该可以帮到你在正确的道路上。它给了我对reFiddle.com的期望。

?:内的(?:\D+)可确保非数字组不会被我使用的语言中的子组捕获。