Frage

I have a stream of data that I need to parse. The stream is sent line by line and takes the form:

ID: XXX  Data: XX XX XX XX XX XX XX XX

where the X's are hex characters, ie:

ID: 1F9  Data: AC 12 53 8F 14 11 FF 00 -> For example

The trick is that there are not always 8 data bytes, so any of these transmissions are also possible:

ID: XXX  Data: XX
ID: XXX  Data: XX XX
ID: XXX  Data: XX XX XX 
ID: XXX  Data: XX XX XX XX 
ID: XXX  Data: XX XX XX XX XX 
ID: XXX  Data: XX XX XX XX XX XX 
ID: XXX  Data: XX XX XX XX XX XX XX 
ID: XXX  Data: XX XX XX XX XX XX XX XX

I want to write a regular expression that can parse out the ID and the available data bytes from each transmission. I then need to store the bytes in an array to assign to a dataGridView.

How would the pattern be written to accomplish this? Is there a better way to assign the values to a row in a dataGridView than assigning to an array? Execution time needs to be optimized.

Thanks!

War es hilfreich?

Lösung

You can use the code below. It first splits the input string and then selects the values into proper variables:

Note: you can use split variable directly, you ID is in index 1 and values start at 2. Ignore the first element as it contains an empty string.

String input = "ID: 1F9  Data: AC 12 53 8F 14 11 FF 00";
String pattern = @"ID:\s|\s\sData:\s|\s";

string[] split = Regex.Split(input, pattern);
string id = split[1]; // the first elements contains "" so ignore it
string[] values = new string[split.Length - 2];
for (int i = 2; i < split.Length; i++)
    values[i - 2] = split[i];
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top