简体   繁体   中英

How to split string by multiple strings if followed by specific character

I receive bytecode and try to interpret it. Since this is a communication between two devices using the HART protocol (primary/secondary), I wanted to sort the bytes first.

A request which starts with 82 and the answer which starts with 86. Between them can be any number of FFs (Depending on how many come through), which serve as preambles.

Here is an example output:

82 05 C6 00 46 5D 03 00 59  FF FF FF FF FF 86 05 C6 00 46 5D 03 1A 00 00 41 4C BE B2 3B 40 F6 4D B7 24 C2 23 B2 40 20 41 B5 BA 3D AA 7F A0 00 00 20 FF FF FF FF 
82 05 C6 00 46 5D 03 00 59     FF FF FF FF 86 05 C6 00 46 5D 03 1A 00 00 41 4C BE D5 3B 40 F6 4D F5 24 C2 23 B2 40 20 41 B5 63 04 AA 7F A0 00 00 E5 FF FF FF FF 
82 05 C6 00 46 5D 03 00 59  FF FF FF FF FF 86 05 C6 00 46 5D 03 1A 00 00 41 4C BE F6 3B 40 F6 4E 2E 24 C2 23 B2 40 20 41 B5 76 E7 AA 7F A0 00 00 E8 FF FF FF FF 
82 05 C6 00 46 5D 03 00 59  FF FF FF FF FF 86 05 C6 00 46 5D 03 1A 00 00 41 4C BF 01 3B 40 F6 4E 41 24 C2 23 B2 40 20 41 B5 67 34 AA 7F A0 00 00 B3 FF FF FF FF

Here is my attempt to separate the requests and responses:

string[] delimiterChars = {
    "FF FF FF FF FF FF FF FF FF FF ",
    "FF FF FF FF FF FF FF FF FF ",
    "FF FF FF FF FF FF FF FF ",
    "FF FF FF FF FF FF FF ",
    "FF FF FF FF FF FF ",
    "FF FF FF FF FF ",
    "FF FF FF FF ",
    "FF FF FF ",
    "FF FF ",
    "FF "
};

string[] words = OnlyHex.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);

This works fine, but unfortunately there can be FFs in the messages, which my code does not catch.

I could add these to each string array entry of delimiterChars but I don't think that would be the prettiest solution and would make it impossible to separate the request from the response as the numbers would then be missing.

How could I make it so that the string is only spearated, if the following part starts with an 82 or 86? The 82 and 86 should be still in the split string. The FFs do not have to.

Probably the solution is Regex, but unfortunately I'm not a pro at it.

You can indeed use regex for that. It will look something like this:

var match = Regex.Match(input[0], "(?<request>82.*)(?<answer>86.*)");
var request = match.Groups["request"].Value; // empty string for invalid input
var answer = match.Groups["answer"].Value;   // empty string for invalid input

It seems however strange that you are using strings to store this type of data. A byte array seems better feet, but then you cannot any longer use regex.

I suppose you will be using the answer and response later on, so your problem seems like a good candidate for parser generators. I suggest you look at Sprache or Superpower .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM