Search code examples
c#textverification

Verify the text of a file matches a certain format


I need to verify that the text of a file contains text in the following format:

#0
DIRECTION: FORWARD
SPEED: 10
TIME: 10

OR

#1
DIRECTION: REVERSE
SPEED: 10
ROTATIONS: 10

And this will repeat with multiple steps.

Where # must be followed by a number, DIRECTION must be followed by FORWARD or REVERSE, SPEED must be followed by a number and the last line will be either TIME or ROTATIONS followed by a number.

I want to verify that the file contains this text in this format and not some weird values before I start reading in the values.
Can I use some type of wild card? I have started looking at Regex, but I have not worked with it before.
What I would like to do is do some type of comparison where the number are wildcards, that way I know if the lines contain the basic formatting:

if(fileLines[0].Matches("#%")) // Where % would be the wildcard?  
if(fileLines[1].Matches("DIRECTION:%")) // Does something like this exist?

Solution

  • This patterns seems to work

        string[] lines = 
        {
            "#0",
            "DIRECTION: FORWARD",
            "SPEED: 10",
            "TIME: 10"
        };
    
          // meaning At start of line there is a # followed by digits till the end of line
        if(checkLine(@"^#\d+$", lines[0]) == false)
            Console.WriteLine("False on line 1");
        else
            Console.WriteLine("True on line 1");
    
          // meaning At start of line there is the word DIRECTION: followed by space and the words REVERSE or FORWARD
        if(checkLine(@"^DIRECTION: (REVERSE|FORWARD)", lines[1]) == false)
            Console.WriteLine("False on line 2");
        else
            Console.WriteLine("True on line 2");
    
          // meaning At start of line there is the word SPEED: followed by a space and digits till the end of the line
        if(checkLine(@"^SPEED: \d+$", lines[2]) == false)
            Console.WriteLine("False on line 3");
        else
            Console.WriteLine("True on line 3");
    
          // meaning At start of line there are the words TIME or ROTATIONS followed by colon, space and digits till the end of the line
        if(checkLine(@"^(TIME|ROTATIONS): \d+$", lines[3]) == false)
            Console.WriteLine("False on line 4");
        else
            Console.WriteLine("True on line 4");
    }
    
    // Define other methods and classes here
    private bool checkLine(string regExp, string line)
    {
        Regex r = new Regex(regExp);
        return r.IsMatch(line);
    }