regex C#中解析的简单方法

col17t5w  于 2023-05-08  发布在  C#
关注(0)|答案(3)|浏览(204)

我是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)+)?

我试图提取数据的不同属性,如总呼叫回答平均时间在呼叫
等等,我基本上想为那些类型的字段提取数据,并存储在一个表中。

7qhs6swi

7qhs6swi1#

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

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;}
}
slsn1g29

slsn1g292#

不知道你想做什么,但这里是如何使用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()
 }
1tu0hz3e

1tu0hz3e3#

你在正则表达式中使用了很多.,我建议你避免使用它。相反,通过匹配 [任何不是我**感兴趣的] 来匹配一大组你不感兴趣的字符。在这种情况下,你想要数字,对吗?
我会这样做(\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#必须迭代匹配并提取命名子组的方法,但这应该会让你走上正确的道路。
(?:\D+)中的?:确保非数字组不会被捕获到我使用的语言中的子组中。

相关问题