regex - C#: Read data from txt file -
i have .edf (text) file. file's contents follows:
configfile.sample, software v0.32, cp version 0.32 [123_float][2] [127_number][0] [039_code][70]
i wnat read these items , parse them this:
123_float - 2 127_number - 0 039_code - 70
how can using c#?
well, might start file.readalllines()
method. then, iterate through lines in file, checking see if match pattern. if do, extract necessary text , whatever want it.
here's example assumes want lines in format [(field 1)][(field 2)]
:
// or wherever file located string path = @"c:\myfile.edf"; // pattern check each line regex pattern = new regex(@"\[([^\]]*?)\]"); // read in lines string[] lines = file.readalllines(path); // iterate through lines foreach (string line in lines) { // check if line matches format here var matches = pattern.matches(line); if (matches.count == 2) { string value1 = matches[0].groups[1].value; string value2 = matches[1].groups[1].value; console.writeline(string.format("{0} - {1}", value1, value2)); } }
this outputs them console window, whatever want value1
, value2
(write them file, store them in data structure, etc).
also, please note regular expressions not strong point -- there's more elegant way check if line matches pattern :)
if want more info, check out msdn's article on reading data text file starting point.
Comments
Post a Comment