1

Usually, we can easily get a String value between two characters. My question is, how do I get the value between two same characters.

For example:

String full_value = "http://stackoverflow.com/questions/9367119/title-goes-here";

In this example, how can I extract the value 9367119 from the entire string?

The solution that I use doesn't work since 9367119 has the same / characters to the right and left of it.

Here's what I have so far:

This works for values that doesn't have two same characters to the left and right. Such as: /dog\ I can easily replace / and \ with my solution

public static string Between(string full_value, string a, string b)
{
        int posA = full_value.IndexOf(a);
        int posB = full_value.LastIndexOf(b);
        if (posA == -1)
        {
            return "";
        }
        if (posB == -1)
        {
            return "";
        }
        int adjustedPosA = posA + a.Length;
        if (adjustedPosA >= posB)
        {
            return "";
        }
        return full_value.Substring(adjustedPosA, posB - adjustedPosA);
    }
Jay
  • 4,873
  • 7
  • 72
  • 137
  • 1
    why don't you split the string based on the `/` separator and get the penultimate slice? – fedorqui May 09 '16 at 10:52
  • Sorry I'm not sure I understood what you meant? @fedorqui – Jay May 09 '16 at 10:52
  • Please redefine your requirements. It does not confirm to your example. Your example should be returning a string array of `stackoverflow.com`, `questions` and `9367119`. – CodeCaster May 09 '16 at 10:54
  • Maybe you want to have a look at _Uri.Segments_ https://msdn.microsoft.com/en-us/library/system.uri.segments(v=vs.110).aspx – schlonzo May 09 '16 at 10:55

3 Answers3

3

You could just Split and get the relevant part:

string s = "http://stackoverflow.com/questions/9367119/title-goes-here";
string[] sp = s.Split('/');
Console.WriteLine(sp[4]);

IdeOne demo.

AKS
  • 18,983
  • 3
  • 43
  • 54
  • Yes ended up coding the same thing after @fedorqui's comment. Thanks! I will accept this in a bit – Jay May 09 '16 at 10:56
  • Thanks I didn't see the comment till I post the solution. – AKS May 09 '16 at 10:57
  • Maybe `s.Split(new[] {"/"}, StringSplitOptions.RemoveEmptyEntries).Where(m => m.All(p => Char.IsDigit(p))).FirstOrDefault()`? You won't have to check if the all-digit chunk is the 5th element in the string. Unless you know it will always be there. – Wiktor Stribiżew May 09 '16 at 11:08
1

Use following regex:

(?<=/)\d+(?=/)

String full_value = "http://stackoverflow.com/questions/9367119/title-goes-here";
var matches = Regex.Matches(full_value, @"(?<=/)\d+(?=/)");
M.S.
  • 4,283
  • 1
  • 19
  • 42
1

try this way use Split

 string s = "http://stackoverflow.com/questions/9367119/title-goes-here";
    string[] sps = s.Split('/');
    foreach(string sp in sps ){
     if(sp =="9367119"){
       Console.WriteLine(sp);
      }
    }
Nazmul Hasan
  • 10,130
  • 7
  • 50
  • 73