I need to transfer data from MATLAB to a C# software. The data from MATLAB should also be editable offline (i.e. outside MATLAB and the C# software). To achieve this, my MATLAB code prints the data with readable patterns to a text file. For example:
<L> pt: [0.001,2,3], spd: 100, cfg: fut, daq: on, id: [1,1] </L>
<L> pt: [0.002,3,4], cfg: nut, spd: 100, id: [1,1], daq: on</L>
<C> pt: [0.02,5,3], spd: 100, daq: on, id: [1,1] </C>
<L> pt: [1.002,3,4], spd: 100, daq: off</L>
In C#, I want to parse each line, extract these keywords and assign them to properties:
enum PathType { L, C}
class Path
{
public PathType Type { get; set; }
public float[] Pt { get; set; }
public int Spd { get; set; }
public string Cfg { get; set; }
public bool Daq { get; set; }
public int[] Id { get; set; }
}
So for Line 1, I intend to have something look like this:
var path = new Path {
PathType = PathType.L,
Pt = new []{ 0.001, 2, 3 },
Spd = 100,
Cfg = "fut",
Daq = true,
Id = new []{ 1, 1 }};
for Line 4:
var path = new Path {
PathType = PathType.L,
Pt = new []{ 1.002, 3, 4 },
Spd = 100,
Cfg = null,
Daq = false,
Id = null;
Since the keywords are arranged in different order and may not appear in all lines, I can't use a single regular expression to extract these information. I have to use multiple regular expressions to test each line:
var typeReg = new Regex(@"<(\w+)>");
var ptReg = new Regex(@"pt:\s+(?<open>\[)[^\[]*(?<close-open>\])(?(open))");
var spdReg = new Regex(@"spd:\s+(\d+)");
var cfgReg = new Regex(@"cfg:\s+(fut|nut)");
var daqReg = new Regex(@"daq:\s+(on|off)");
var idReg = new Regex(@"id:\s+(?<open>\[)[^\[]*(?<close-open>\])(?(open))");
This works but I'm wondering if there is any better way of doing this?
Shall I print the data in a different pattern such as:
L; pt: [0.001,2,3]; spd: 100; cfg: fut; daq: on; id: [1,1]
Then I can split the string with delimiter ;
and then check each substring with x.StartWith('...')
. But this way, I feel it is not as readable as the current pattern.
I do not want to use xml
since it will make the text file bigger than the desired size.