Reputation: 647
How can I split a string based on a custom delimiter while also ensuring that the string ends with a delimiter? I am trying to process incoming client data and trying to divide up the messages. But it is possible that the client sends the server a message that is comprised of 3 smaller messages, where the third message is not yet complete. ie it does not contain the delimiter, meaning more is to come.
Example
using System;
public class Test{
private string eofString = "<EOF>";
private string[] eofArray = { "<EOF>" };
public void Main(){
string foo = "bob<EOF>jill<EOF>jake";
string[] splitMessages = foo.Split(eofArray, StringSplitOptions.RemoveEmptyEntries);
for(int i = 0; i < splitMessages.Length; i++){
Console.WriteLine(splitMessages[i]);
}
}
}
Outputs
bob
jill
jake
My expected output is
bob
jill
because the end of the string foo
did not end with <EOF>
.
Which is wrong. I want to put jake
in this case back into a string builder.
Upvotes: 0
Views: 146
Reputation: 2932
If you wanted a regex based solution the following will work as well.
string input = "bob<EOF>jill<EOF>jake";
Regex r = new Regex(@"(?<message>.+?)\<EOF\>", RegexOptions.Compiled);
IEnumerable<string> messages = r.Matches(input).Cast<Match>().Select(i => i.Groups["message"].Value);
Basically it is using a non-greedy match pattern .+?
(1 or more of any character, matching as few characters as possible) within a named captured group (?<message> #pattern goes here)
that must be terminated with the fixed string <EOF>
. All of the matches are found in one "pass" and just need to be projected out of the match collection by the name of the capture group.
Upvotes: 0
Reputation: 7344
You can use String.EndsWith to determine if string ends with the delimiter.
Upvotes: 1