'Get last word of string that starts with 5555/ and ends with 0/

I have a string containg double data that is being sent by sockets. Due to network delay I get overloaded data on the client side, meaning my actual string is

5555/57.6626/63.364/0/

and I get this string on client side:

5555/989.994/262.65645/0/5555/165.6515/6526.545/0/

So basically two strings are merged. I want the last updated string that is in bold format.

Note that 5555/ and /0/ are the delimiters, my actual data is between these delimiters.



Solution 1:[1]

var s = "5555/989.994/262.65645/0/5555/165.6515/6526.545/0/";
var x = s.Substring(s.LastIndexOf("5555/") + 5).
    Substring(0, s.LastIndexOf("0/") - s.LastIndexOf("5555") - 5);

result:

165.6515/6526.545/

Solution 2:[2]

another variant

var s = "5555/989.994/262.65645/0/5555/165.6515/6526.545/0/";
var x = s.Split("5555/").Last().Split("0/")[0];

C# 8.0

var x = s.Split("5555/")[^1].Split("0/")[0];

Solution 3:[3]

To get the last occurrence, and given that

data between /5555 and /0/ can not ever be 5555 and 0

you can use a pattern matching 5555/ and then assert no more occurrences of that part to the right using a negative lookahead (?!\S*/5555/)

Then match until /0/. As there are no spaces in the example string, you can use \S* to match optional non whitespace characters.

var input = "5555/989.994/262.65645/0/5555/165.6515/6526.545/0/";
var m = Regex.Match(input, @"5555/(?!\S*/5555/)\S*/0/");
if (m.Success) {
    Console.WriteLine(m.Value);
}

Output

5555/165.6515/6526.545/0/

Solution 4:[4]

You could use a regular expression:

Regex.Matches(input, @"(?<=(^|/)5555/)[\d\./]+?(?=/0(/|$))")

Explanation:

  • (?<=(^|/)5555/) will check for "5555/" at the beginning of the input or after a "/", but not include this in the match
  • [\d\./]+? will match any sequence of digits, dots and slashes (the ? is for a non-greedy match, i.e. the shortest match possible)
  • (?=/0(/|$)) will check for "/0" at the end of the input or preceding a "/", but not include this in the match

This will produce two matches "989.994/262.65645" and "165.6515/6526.545"; just take the last one.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 The fourth bird
Solution 4 Klaus Gütter