Help me parsing the following file format

2019-09-16 21:07发布

问题:

I need to parse third party text file in the following format

WE BUY  : 10 000.00 USD                      
VALUE   : 281210
RATE    : 30.2600

So the general pattern is

TAG,some separator,:,someseparator,VALUE

Let;s say i started with File.ReadAllLines so I am dealing with individual lines.

What is the best way to parse values?

UPDATE

I don't have any documentation for the format but let's say that it is position-based.

1) ":" is always 9th charcter in the string, 2) VALUE is 11th character. 3) Unused spaces are filled with space character.

Let's talk about that format.

UPDATE 2

I am thinking about if RegEx is better here? For instance let's say I have a subtask find

RATE : 30.2600

in the whole text and extract 30.2600 given that is starts with 11th character

回答1:

For Each line:

   string[]  parts = line.Split(':');
   // assert parts.Length == 2
   string tag = parts[0].Trim();
   string[] values = parts[1].Split(' ', SplitOptions.NoDupes);  // or ','


回答2:

Regarding the parsing of the data read from file, consider using Regular Expressions. In this case you have to be alert though for the delimiter i.e. make sure the delimiter (: in our case) is not accidentally found in the tag or value parts.


            string pattern = "^(?<TAG>[^:]+):(?<VALUE>.+)$";

        string dataReadFromFile = "WE BUY  : 10 000.00 USD\r\nVALUE   : 281210 \r\nRATE    : 30.2600\r\n";

        Regex rx = new Regex(pattern, RegexOptions.Multiline); // Multiline important

        MatchCollection mc = rx.Matches(dataReadFromFile);

        foreach (Match m in mc)
        {
            Console.WriteLine("{0}->{1}", m.Groups["TAG"].Value.Trim(), m.Groups["VALUE"].Value.Trim());
        }

Try this and see if it works for you. If not tell me more info to update it. Hope it will be usefull.