Search code examples
c#parsingenumsstring-parsing

c# string text, enum type


I am reading txt file, and I would like to separate it into some parts. This example of my TXT file:

"Part error(1) devic[3].data_type(2)"
"Escape error(3) device[10].data_type(12)"

I want to achieve such a situation that, when I have first word "Part" I would like to have enum type for it, and in switch I would like to call some function that will work with whole line, and on the other hand, when I will have first word "Escape", there will another case in switch that will call other functions. How can I do it? This is my code so far:

class Row
{
    public enum Category { Part, Escape }
    public string Error{ get; set; }
    public string Data_Type { get; set; }
    public string Device{ get; set; }
}

public object HandleRegex(string items)
{
        Row sk = new Row();
        Regex r = new Regex(@"[.]");
        var newStr = r.Replace(items, @" ");

        switch(this.category)
        {
            case Category.Part:
                //I want to call here function HandlePart with my line as a parameter
                HandlePart(newStr);
                break;
            case Category.Escape:
                //Here I want to call Function HandleEscape for line with "Escape" word
                HandleEscape(newStr);
                break;

        }
}

Solution

  • public object HandleRegex(string items)
    {        
        Regex r = new Regex(@"[.]");
        var newStr = r.Replace(items, @" ");
        try {
         category = (Category) new EnumConverter(typeof(Category)).ConvertFromString(items.Split(new string[]{" "},StringSplitOptions.RemoveEmptyEntries)[0]);
            }
        catch {
           throw new ArgumentException("items doesn't contain valid prefix");
        }
        switch(category)
        {
            case Category.Part:
                HandlePart(newStr);
                break;
            case Category.Escape:
                HandleEscape(newStr);
                break;
        }
     }