Get string between two strings in a string












70















I have a string like:



"super exemple of string key : text I want to keep - end of my string"


I want to just keep the string which is between "key : " and " - ". How can I do that? Must I use a Regex or can I do it in another way?










share|improve this question




















  • 1





    use substring and indexof

    – Sayse
    Jun 22 '13 at 16:02











  • Get the string after a particular string in a string and before another specific string which is also contained in the string where the former string is in ..

    – Ken Kin
    Jun 22 '13 at 16:59
















70















I have a string like:



"super exemple of string key : text I want to keep - end of my string"


I want to just keep the string which is between "key : " and " - ". How can I do that? Must I use a Regex or can I do it in another way?










share|improve this question




















  • 1





    use substring and indexof

    – Sayse
    Jun 22 '13 at 16:02











  • Get the string after a particular string in a string and before another specific string which is also contained in the string where the former string is in ..

    – Ken Kin
    Jun 22 '13 at 16:59














70












70








70


7






I have a string like:



"super exemple of string key : text I want to keep - end of my string"


I want to just keep the string which is between "key : " and " - ". How can I do that? Must I use a Regex or can I do it in another way?










share|improve this question
















I have a string like:



"super exemple of string key : text I want to keep - end of my string"


I want to just keep the string which is between "key : " and " - ". How can I do that? Must I use a Regex or can I do it in another way?







c# regex string






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 12 '17 at 19:51









Servy

178k18236349




178k18236349










asked Jun 22 '13 at 16:00









flowflow

1,63841937




1,63841937








  • 1





    use substring and indexof

    – Sayse
    Jun 22 '13 at 16:02











  • Get the string after a particular string in a string and before another specific string which is also contained in the string where the former string is in ..

    – Ken Kin
    Jun 22 '13 at 16:59














  • 1





    use substring and indexof

    – Sayse
    Jun 22 '13 at 16:02











  • Get the string after a particular string in a string and before another specific string which is also contained in the string where the former string is in ..

    – Ken Kin
    Jun 22 '13 at 16:59








1




1





use substring and indexof

– Sayse
Jun 22 '13 at 16:02





use substring and indexof

– Sayse
Jun 22 '13 at 16:02













Get the string after a particular string in a string and before another specific string which is also contained in the string where the former string is in ..

– Ken Kin
Jun 22 '13 at 16:59





Get the string after a particular string in a string and before another specific string which is also contained in the string where the former string is in ..

– Ken Kin
Jun 22 '13 at 16:59












16 Answers
16






active

oldest

votes


















101














Perhaps, a good way is just to cut out a substring:



String St = "super exemple of string key : text I want to keep - end of my string";

int pFrom = St.IndexOf("key : ") + "key : ".Length;
int pTo = St.LastIndexOf(" - ");

String result = St.Substring(pFrom, pTo - pFrom);





share|improve this answer

































    28














    string input = "super exemple of string key : text I want to keep - end of my string";
    var match = Regex.Match(input, @"key : (.+?)-").Groups[1].Value;


    or with just string operations



    var start = input.IndexOf("key : ") + 6;
    var match2 = input.Substring(start, input.IndexOf("-") - start);





    share|improve this answer

































      21














      You can do it without regex



       input.Split(new string {"key :"},StringSplitOptions.None)[1]
      .Split('-')[0]
      .Trim();





      share|improve this answer



















      • 1





        This is the best option thx ;)

        – Soheyl
        Jan 6 at 0:57



















      11














      Depending on how robust/flexible you want your implementation to be, this can actually be a bit tricky. Here's the implementation I use:



      public static class StringExtensions {
      /// <summary>
      /// takes a substring between two anchor strings (or the end of the string if that anchor is null)
      /// </summary>
      /// <param name="this">a string</param>
      /// <param name="from">an optional string to search after</param>
      /// <param name="until">an optional string to search before</param>
      /// <param name="comparison">an optional comparison for the search</param>
      /// <returns>a substring based on the search</returns>
      public static string Substring(this string @this, string from = null, string until = null, StringComparison comparison = StringComparison.InvariantCulture)
      {
      var fromLength = (from ?? string.Empty).Length;
      var startIndex = !string.IsNullOrEmpty(from)
      ? @this.IndexOf(from, comparison) + fromLength
      : 0;

      if (startIndex < fromLength) { throw new ArgumentException("from: Failed to find an instance of the first anchor"); }

      var endIndex = !string.IsNullOrEmpty(until)
      ? @this.IndexOf(until, startIndex, comparison)
      : @this.Length;

      if (endIndex < 0) { throw new ArgumentException("until: Failed to find an instance of the last anchor"); }

      var subString = @this.Substring(startIndex, endIndex - startIndex);
      return subString;
      }
      }

      // usage:
      var between = "a - to keep x more stuff".Substring(from: "-", until: "x");
      // returns " to keep "





      share|improve this answer


























      • I used your code, but I found a small bug when at @this.IndexOf(until, startIndex + fromLength, comparison) from strings like „AB” where A is from and B is until, so I removed + fromLength. I haven't tested it deeply though

        – Adrian Iftode
        Oct 16 '13 at 11:21






      • 1





        @AdrianIftode: good call. This was definitely a bug. It makes sense to start the search for the second anchor at startIndex, since that's already past the end of the first anchor. I've fixed the code here.

        – ChaseMedallion
        Oct 16 '13 at 12:16











      • InvariantCulture isn't working with Windows Universal Apps. Is there any way to remove it with keeping the functionality of your class? @ChaseMedallion

        – Leon
        Sep 12 '15 at 17:02











      • @Leon: you should be able to rip out all the culture-related stuff and .NET will just use the current culture for the indexOf operation. I'm not familiar with Windows Universal Apps, though, so I can't say for sure.

        – ChaseMedallion
        Sep 17 '15 at 12:27



















      10














      Regex is overkill here.



      You could use string.Split with the overload that takes a string for the delimiters but that would also be overkill.



      Look at Substring and IndexOf - the former to get parts of a string given and index and a length and the second for finding indexed of inner strings/characters.






      share|improve this answer



















      • 2





        It's not overkill... in fact I would say Substring and IndexOf are underkill. I'd say that string.Split is about right. Regex is overkill.

        – It'sNotALie.
        Jun 22 '13 at 16:22






      • 2





        The point of it being overkill or under-kill is moot, because the answer fulfills the poster's request of doing it another way than Regex.

        – Karl Anderson
        Jun 22 '13 at 16:29






      • 2





        @newStackExchangeInstance: it also fails if there is a " - " before the " key : ". Substring is spot on.

        – jmoreno
        Jun 22 '13 at 17:16











      • It shouldn't if you know how to write regex...

        – It'sNotALie.
        Jun 22 '13 at 17:16











      • @newStackExchangeInstance - I believe he is talking about string.Split.

        – Oded
        Jun 22 '13 at 17:18



















      8














      Here is the way how i can do that



         public string Between(string STR , string FirstString, string LastString)
      {
      string FinalString;
      int Pos1 = STR.IndexOf(FirstString) + FirstString.Length;
      int Pos2 = STR.IndexOf(LastString);
      FinalString = STR.Substring(Pos1, Pos2 - Pos1);
      return FinalString;
      }





      share|improve this answer































        7














        I think this works:



           static void Main(string args)
        {
        String text = "One=1,Two=2,ThreeFour=34";

        Console.WriteLine(betweenStrings(text, "One=", ",")); // 1
        Console.WriteLine(betweenStrings(text, "Two=", ",")); // 2
        Console.WriteLine(betweenStrings(text, "ThreeFour=", "")); // 34

        Console.ReadKey();

        }

        public static String betweenStrings(String text, String start, String end)
        {
        int p1 = text.IndexOf(start) + start.Length;
        int p2 = text.IndexOf(end, p1);

        if (end == "") return (text.Substring(p1));
        else return text.Substring(p1, p2 - p1);
        }





        share|improve this answer
























        • Great solution. Thanks!

          – arcee123
          Aug 31 '18 at 0:53



















        5














         string str="super exemple of string key : text I want to keep - end of my string";
        int startIndex = str.IndexOf("key") + "key".Length;
        int endIndex = str.IndexOf("-");
        string newString = str.Substring(startIndex, endIndex - startIndex);





        share|improve this answer



















        • 1





          Your code would result in the colon being returned at the beginning of the newString.

          – tsells
          Jun 23 '13 at 2:18



















        5














        or, with a regex.



        using System.Text.RegularExpressions;

        ...

        var value =
        Regex.Match(
        "super exemple of string key : text I want to keep - end of my string",
        "key : (.*) - ")
        .Groups[1].Value;


        with a running example.



        You can decide if its overkill.



        or



        as an under validated extension method



        using System.Text.RegularExpressions;

        public class Test
        {
        public static void Main()
        {
        var value =
        "super exemple of string key : text I want to keep - end of my string"
        .Between(
        "key : ",
        " - ");

        Console.WriteLine(value);
        }
        }

        public static class Ext
        {
        static string Between(this string source, string left, string right)
        {
        return Regex.Match(
        source,
        string.Format("{0}(.*){1}", left, right))
        .Groups[1].Value;
        }
        }





        share|improve this answer

































          4














          A working LINQ solution:



          string str = "super exemple of string key : text I want to keep - end of my string";
          string res = new string(str.SkipWhile(c => c != ':')
          .Skip(1)
          .TakeWhile(c => c != '-')
          .ToArray()).Trim();
          Console.WriteLine(res); // text I want to keep





          share|improve this answer
























          • super easy solution.thank you.

            – Erdinç
            Nov 12 '16 at 18:59













          • Does this works for single-character placeholders only?

            – beppe9000
            Oct 6 '17 at 21:50



















          3














          Since the : and the - are unique you could use:



          string input;
          string output;
          input = "super example of string key : text I want to keep - end of my string";
          output = input.Split(new char { ':', '-' })[1];





          share|improve this answer


























          • This answer doesn't add anything meaningful to the already big amount of existing answers.

            – Mephy
            Apr 8 '15 at 19:59



















          2














          You can use the extension method below:



          public static string GetStringBetween(this string token, string first, string second)
          {
          if (!token.Contains(first)) return "";

          var afterFirst = token.Split(new { first }, StringSplitOptions.None)[1];

          if (!afterFirst.Contains(second)) return "";

          var result = afterFirst.Split(new { second }, StringSplitOptions.None)[0];

          return result;
          }


          Usage is:



          var token = "super exemple of string key : text I want to keep - end of my string";
          var keyValue = token.GetStringBetween("key : ", " - ");





          share|improve this answer































            1














            You already have some good answers and I realize the code I am providing is far from the most efficient and clean. However, I thought it might be useful for educational purposes. We can use pre-built classes and libraries all day long. But without understanding the inner-workings, we are simply mimicking and repeating and will never learn anything. This code works and is more basic or "virgin" than some of the others:



            char startDelimiter = ':';
            char endDelimiter = '-';

            Boolean collect = false;

            string parsedString = "";

            foreach (char c in originalString)
            {
            if (c == startDelimiter)
            collect = true;

            if (c == endDelimiter)
            collect = false;

            if (collect == true && c != startDelimiter)
            parsedString += c;
            }


            You end up with your desired string assigned to the parsedString variable. Keep in mind that it will also capture proceeding and preceding spaces. Remember that a string is simply an array of characters that can be manipulated like other arrays with indices etc.



            Take care.






            share|improve this answer
























            • This is the best algorithm although the worst in string creation. All the answers provided that are not regex-only are trigger-happy at creating strings but this one is the worst of all in that sense. If you had just captured the beginning an end of the string to capture and used ''string.Substring'' to extract it, it would be perfect.

              – Paulo Morgado
              Jun 23 '13 at 0:12













            • I agree. As I mentioned, it is far from efficient. I wouldn't recommend using this algorithm. It is simply ""dumbing it down" so he can understand strings at a lower level. If he simply wants to get the job done, he already had answers that would achieve that.

              – flyNflip
              Jun 24 '13 at 16:00











            • I understood that. I was just pointing out its strong and week points. Although, to answer the original question it requires a bit more as it need to match a string boundaries and not just character boundaries. But the idea is just the same.

              – Paulo Morgado
              Jun 24 '13 at 20:53











            • Absolutely. You are right on target.

              – flyNflip
              Jun 24 '13 at 21:24



















            1














            var matches = Regex.Matches(input, @"(?<=key :)(.+?)(?=-)");


            This returns only the value(s) between "key :" and the following occurance of "-"






            share|improve this answer































              0














              As I always say nothing is impossible:



              string value =  "super exemple of string key : text I want to keep - end of my string";
              Regex regex = new Regex(@"(key : (.*?) _ )");
              Match match = regex.Match(value);
              if (match.Success)
              {
              Messagebox.Show(match.Value);
              }



              Remeber that should add reference of System.Text.RegularExpressions




              Hope That I Helped.






              share|improve this answer































                0














                If you are looking for a 1 line solution, this is it:



                s.Substring(s.IndexOf("eT") + "eT".Length).Split("97".ToCharArray()).First()


                The whole 1 line solution, with System.Linq:



                using System;
                using System.Linq;

                class OneLiner
                {
                static void Main()
                {
                string s = "TextHereTisImortant973End"; //Between "eT" and "97"
                Console.WriteLine(s.Substring(s.IndexOf("eT") + "eT".Length)
                .Split("97".ToCharArray()).First());
                }
                }





                share|improve this answer

























                  Your Answer






                  StackExchange.ifUsing("editor", function () {
                  StackExchange.using("externalEditor", function () {
                  StackExchange.using("snippets", function () {
                  StackExchange.snippets.init();
                  });
                  });
                  }, "code-snippets");

                  StackExchange.ready(function() {
                  var channelOptions = {
                  tags: "".split(" "),
                  id: "1"
                  };
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function() {
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled) {
                  StackExchange.using("snippets", function() {
                  createEditor();
                  });
                  }
                  else {
                  createEditor();
                  }
                  });

                  function createEditor() {
                  StackExchange.prepareEditor({
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: true,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader: {
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  },
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  });


                  }
                  });














                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function () {
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f17252615%2fget-string-between-two-strings-in-a-string%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  16 Answers
                  16






                  active

                  oldest

                  votes








                  16 Answers
                  16






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  101














                  Perhaps, a good way is just to cut out a substring:



                  String St = "super exemple of string key : text I want to keep - end of my string";

                  int pFrom = St.IndexOf("key : ") + "key : ".Length;
                  int pTo = St.LastIndexOf(" - ");

                  String result = St.Substring(pFrom, pTo - pFrom);





                  share|improve this answer






























                    101














                    Perhaps, a good way is just to cut out a substring:



                    String St = "super exemple of string key : text I want to keep - end of my string";

                    int pFrom = St.IndexOf("key : ") + "key : ".Length;
                    int pTo = St.LastIndexOf(" - ");

                    String result = St.Substring(pFrom, pTo - pFrom);





                    share|improve this answer




























                      101












                      101








                      101







                      Perhaps, a good way is just to cut out a substring:



                      String St = "super exemple of string key : text I want to keep - end of my string";

                      int pFrom = St.IndexOf("key : ") + "key : ".Length;
                      int pTo = St.LastIndexOf(" - ");

                      String result = St.Substring(pFrom, pTo - pFrom);





                      share|improve this answer















                      Perhaps, a good way is just to cut out a substring:



                      String St = "super exemple of string key : text I want to keep - end of my string";

                      int pFrom = St.IndexOf("key : ") + "key : ".Length;
                      int pTo = St.LastIndexOf(" - ");

                      String result = St.Substring(pFrom, pTo - pFrom);






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Oct 3 '18 at 12:16

























                      answered Jun 22 '13 at 16:06









                      Dmitry BychenkoDmitry Bychenko

                      107k1093133




                      107k1093133

























                          28














                          string input = "super exemple of string key : text I want to keep - end of my string";
                          var match = Regex.Match(input, @"key : (.+?)-").Groups[1].Value;


                          or with just string operations



                          var start = input.IndexOf("key : ") + 6;
                          var match2 = input.Substring(start, input.IndexOf("-") - start);





                          share|improve this answer






























                            28














                            string input = "super exemple of string key : text I want to keep - end of my string";
                            var match = Regex.Match(input, @"key : (.+?)-").Groups[1].Value;


                            or with just string operations



                            var start = input.IndexOf("key : ") + 6;
                            var match2 = input.Substring(start, input.IndexOf("-") - start);





                            share|improve this answer




























                              28












                              28








                              28







                              string input = "super exemple of string key : text I want to keep - end of my string";
                              var match = Regex.Match(input, @"key : (.+?)-").Groups[1].Value;


                              or with just string operations



                              var start = input.IndexOf("key : ") + 6;
                              var match2 = input.Substring(start, input.IndexOf("-") - start);





                              share|improve this answer















                              string input = "super exemple of string key : text I want to keep - end of my string";
                              var match = Regex.Match(input, @"key : (.+?)-").Groups[1].Value;


                              or with just string operations



                              var start = input.IndexOf("key : ") + 6;
                              var match2 = input.Substring(start, input.IndexOf("-") - start);






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Jun 22 '13 at 16:09

























                              answered Jun 22 '13 at 16:03









                              I4VI4V

                              30.9k34873




                              30.9k34873























                                  21














                                  You can do it without regex



                                   input.Split(new string {"key :"},StringSplitOptions.None)[1]
                                  .Split('-')[0]
                                  .Trim();





                                  share|improve this answer



















                                  • 1





                                    This is the best option thx ;)

                                    – Soheyl
                                    Jan 6 at 0:57
















                                  21














                                  You can do it without regex



                                   input.Split(new string {"key :"},StringSplitOptions.None)[1]
                                  .Split('-')[0]
                                  .Trim();





                                  share|improve this answer



















                                  • 1





                                    This is the best option thx ;)

                                    – Soheyl
                                    Jan 6 at 0:57














                                  21












                                  21








                                  21







                                  You can do it without regex



                                   input.Split(new string {"key :"},StringSplitOptions.None)[1]
                                  .Split('-')[0]
                                  .Trim();





                                  share|improve this answer













                                  You can do it without regex



                                   input.Split(new string {"key :"},StringSplitOptions.None)[1]
                                  .Split('-')[0]
                                  .Trim();






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Jun 22 '13 at 16:06









                                  AnirudhaAnirudha

                                  28.1k54571




                                  28.1k54571








                                  • 1





                                    This is the best option thx ;)

                                    – Soheyl
                                    Jan 6 at 0:57














                                  • 1





                                    This is the best option thx ;)

                                    – Soheyl
                                    Jan 6 at 0:57








                                  1




                                  1





                                  This is the best option thx ;)

                                  – Soheyl
                                  Jan 6 at 0:57





                                  This is the best option thx ;)

                                  – Soheyl
                                  Jan 6 at 0:57











                                  11














                                  Depending on how robust/flexible you want your implementation to be, this can actually be a bit tricky. Here's the implementation I use:



                                  public static class StringExtensions {
                                  /// <summary>
                                  /// takes a substring between two anchor strings (or the end of the string if that anchor is null)
                                  /// </summary>
                                  /// <param name="this">a string</param>
                                  /// <param name="from">an optional string to search after</param>
                                  /// <param name="until">an optional string to search before</param>
                                  /// <param name="comparison">an optional comparison for the search</param>
                                  /// <returns>a substring based on the search</returns>
                                  public static string Substring(this string @this, string from = null, string until = null, StringComparison comparison = StringComparison.InvariantCulture)
                                  {
                                  var fromLength = (from ?? string.Empty).Length;
                                  var startIndex = !string.IsNullOrEmpty(from)
                                  ? @this.IndexOf(from, comparison) + fromLength
                                  : 0;

                                  if (startIndex < fromLength) { throw new ArgumentException("from: Failed to find an instance of the first anchor"); }

                                  var endIndex = !string.IsNullOrEmpty(until)
                                  ? @this.IndexOf(until, startIndex, comparison)
                                  : @this.Length;

                                  if (endIndex < 0) { throw new ArgumentException("until: Failed to find an instance of the last anchor"); }

                                  var subString = @this.Substring(startIndex, endIndex - startIndex);
                                  return subString;
                                  }
                                  }

                                  // usage:
                                  var between = "a - to keep x more stuff".Substring(from: "-", until: "x");
                                  // returns " to keep "





                                  share|improve this answer


























                                  • I used your code, but I found a small bug when at @this.IndexOf(until, startIndex + fromLength, comparison) from strings like „AB” where A is from and B is until, so I removed + fromLength. I haven't tested it deeply though

                                    – Adrian Iftode
                                    Oct 16 '13 at 11:21






                                  • 1





                                    @AdrianIftode: good call. This was definitely a bug. It makes sense to start the search for the second anchor at startIndex, since that's already past the end of the first anchor. I've fixed the code here.

                                    – ChaseMedallion
                                    Oct 16 '13 at 12:16











                                  • InvariantCulture isn't working with Windows Universal Apps. Is there any way to remove it with keeping the functionality of your class? @ChaseMedallion

                                    – Leon
                                    Sep 12 '15 at 17:02











                                  • @Leon: you should be able to rip out all the culture-related stuff and .NET will just use the current culture for the indexOf operation. I'm not familiar with Windows Universal Apps, though, so I can't say for sure.

                                    – ChaseMedallion
                                    Sep 17 '15 at 12:27
















                                  11














                                  Depending on how robust/flexible you want your implementation to be, this can actually be a bit tricky. Here's the implementation I use:



                                  public static class StringExtensions {
                                  /// <summary>
                                  /// takes a substring between two anchor strings (or the end of the string if that anchor is null)
                                  /// </summary>
                                  /// <param name="this">a string</param>
                                  /// <param name="from">an optional string to search after</param>
                                  /// <param name="until">an optional string to search before</param>
                                  /// <param name="comparison">an optional comparison for the search</param>
                                  /// <returns>a substring based on the search</returns>
                                  public static string Substring(this string @this, string from = null, string until = null, StringComparison comparison = StringComparison.InvariantCulture)
                                  {
                                  var fromLength = (from ?? string.Empty).Length;
                                  var startIndex = !string.IsNullOrEmpty(from)
                                  ? @this.IndexOf(from, comparison) + fromLength
                                  : 0;

                                  if (startIndex < fromLength) { throw new ArgumentException("from: Failed to find an instance of the first anchor"); }

                                  var endIndex = !string.IsNullOrEmpty(until)
                                  ? @this.IndexOf(until, startIndex, comparison)
                                  : @this.Length;

                                  if (endIndex < 0) { throw new ArgumentException("until: Failed to find an instance of the last anchor"); }

                                  var subString = @this.Substring(startIndex, endIndex - startIndex);
                                  return subString;
                                  }
                                  }

                                  // usage:
                                  var between = "a - to keep x more stuff".Substring(from: "-", until: "x");
                                  // returns " to keep "





                                  share|improve this answer


























                                  • I used your code, but I found a small bug when at @this.IndexOf(until, startIndex + fromLength, comparison) from strings like „AB” where A is from and B is until, so I removed + fromLength. I haven't tested it deeply though

                                    – Adrian Iftode
                                    Oct 16 '13 at 11:21






                                  • 1





                                    @AdrianIftode: good call. This was definitely a bug. It makes sense to start the search for the second anchor at startIndex, since that's already past the end of the first anchor. I've fixed the code here.

                                    – ChaseMedallion
                                    Oct 16 '13 at 12:16











                                  • InvariantCulture isn't working with Windows Universal Apps. Is there any way to remove it with keeping the functionality of your class? @ChaseMedallion

                                    – Leon
                                    Sep 12 '15 at 17:02











                                  • @Leon: you should be able to rip out all the culture-related stuff and .NET will just use the current culture for the indexOf operation. I'm not familiar with Windows Universal Apps, though, so I can't say for sure.

                                    – ChaseMedallion
                                    Sep 17 '15 at 12:27














                                  11












                                  11








                                  11







                                  Depending on how robust/flexible you want your implementation to be, this can actually be a bit tricky. Here's the implementation I use:



                                  public static class StringExtensions {
                                  /// <summary>
                                  /// takes a substring between two anchor strings (or the end of the string if that anchor is null)
                                  /// </summary>
                                  /// <param name="this">a string</param>
                                  /// <param name="from">an optional string to search after</param>
                                  /// <param name="until">an optional string to search before</param>
                                  /// <param name="comparison">an optional comparison for the search</param>
                                  /// <returns>a substring based on the search</returns>
                                  public static string Substring(this string @this, string from = null, string until = null, StringComparison comparison = StringComparison.InvariantCulture)
                                  {
                                  var fromLength = (from ?? string.Empty).Length;
                                  var startIndex = !string.IsNullOrEmpty(from)
                                  ? @this.IndexOf(from, comparison) + fromLength
                                  : 0;

                                  if (startIndex < fromLength) { throw new ArgumentException("from: Failed to find an instance of the first anchor"); }

                                  var endIndex = !string.IsNullOrEmpty(until)
                                  ? @this.IndexOf(until, startIndex, comparison)
                                  : @this.Length;

                                  if (endIndex < 0) { throw new ArgumentException("until: Failed to find an instance of the last anchor"); }

                                  var subString = @this.Substring(startIndex, endIndex - startIndex);
                                  return subString;
                                  }
                                  }

                                  // usage:
                                  var between = "a - to keep x more stuff".Substring(from: "-", until: "x");
                                  // returns " to keep "





                                  share|improve this answer















                                  Depending on how robust/flexible you want your implementation to be, this can actually be a bit tricky. Here's the implementation I use:



                                  public static class StringExtensions {
                                  /// <summary>
                                  /// takes a substring between two anchor strings (or the end of the string if that anchor is null)
                                  /// </summary>
                                  /// <param name="this">a string</param>
                                  /// <param name="from">an optional string to search after</param>
                                  /// <param name="until">an optional string to search before</param>
                                  /// <param name="comparison">an optional comparison for the search</param>
                                  /// <returns>a substring based on the search</returns>
                                  public static string Substring(this string @this, string from = null, string until = null, StringComparison comparison = StringComparison.InvariantCulture)
                                  {
                                  var fromLength = (from ?? string.Empty).Length;
                                  var startIndex = !string.IsNullOrEmpty(from)
                                  ? @this.IndexOf(from, comparison) + fromLength
                                  : 0;

                                  if (startIndex < fromLength) { throw new ArgumentException("from: Failed to find an instance of the first anchor"); }

                                  var endIndex = !string.IsNullOrEmpty(until)
                                  ? @this.IndexOf(until, startIndex, comparison)
                                  : @this.Length;

                                  if (endIndex < 0) { throw new ArgumentException("until: Failed to find an instance of the last anchor"); }

                                  var subString = @this.Substring(startIndex, endIndex - startIndex);
                                  return subString;
                                  }
                                  }

                                  // usage:
                                  var between = "a - to keep x more stuff".Substring(from: "-", until: "x");
                                  // returns " to keep "






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Oct 16 '13 at 12:16

























                                  answered Jun 22 '13 at 17:59









                                  ChaseMedallionChaseMedallion

                                  11.4k658109




                                  11.4k658109













                                  • I used your code, but I found a small bug when at @this.IndexOf(until, startIndex + fromLength, comparison) from strings like „AB” where A is from and B is until, so I removed + fromLength. I haven't tested it deeply though

                                    – Adrian Iftode
                                    Oct 16 '13 at 11:21






                                  • 1





                                    @AdrianIftode: good call. This was definitely a bug. It makes sense to start the search for the second anchor at startIndex, since that's already past the end of the first anchor. I've fixed the code here.

                                    – ChaseMedallion
                                    Oct 16 '13 at 12:16











                                  • InvariantCulture isn't working with Windows Universal Apps. Is there any way to remove it with keeping the functionality of your class? @ChaseMedallion

                                    – Leon
                                    Sep 12 '15 at 17:02











                                  • @Leon: you should be able to rip out all the culture-related stuff and .NET will just use the current culture for the indexOf operation. I'm not familiar with Windows Universal Apps, though, so I can't say for sure.

                                    – ChaseMedallion
                                    Sep 17 '15 at 12:27



















                                  • I used your code, but I found a small bug when at @this.IndexOf(until, startIndex + fromLength, comparison) from strings like „AB” where A is from and B is until, so I removed + fromLength. I haven't tested it deeply though

                                    – Adrian Iftode
                                    Oct 16 '13 at 11:21






                                  • 1





                                    @AdrianIftode: good call. This was definitely a bug. It makes sense to start the search for the second anchor at startIndex, since that's already past the end of the first anchor. I've fixed the code here.

                                    – ChaseMedallion
                                    Oct 16 '13 at 12:16











                                  • InvariantCulture isn't working with Windows Universal Apps. Is there any way to remove it with keeping the functionality of your class? @ChaseMedallion

                                    – Leon
                                    Sep 12 '15 at 17:02











                                  • @Leon: you should be able to rip out all the culture-related stuff and .NET will just use the current culture for the indexOf operation. I'm not familiar with Windows Universal Apps, though, so I can't say for sure.

                                    – ChaseMedallion
                                    Sep 17 '15 at 12:27

















                                  I used your code, but I found a small bug when at @this.IndexOf(until, startIndex + fromLength, comparison) from strings like „AB” where A is from and B is until, so I removed + fromLength. I haven't tested it deeply though

                                  – Adrian Iftode
                                  Oct 16 '13 at 11:21





                                  I used your code, but I found a small bug when at @this.IndexOf(until, startIndex + fromLength, comparison) from strings like „AB” where A is from and B is until, so I removed + fromLength. I haven't tested it deeply though

                                  – Adrian Iftode
                                  Oct 16 '13 at 11:21




                                  1




                                  1





                                  @AdrianIftode: good call. This was definitely a bug. It makes sense to start the search for the second anchor at startIndex, since that's already past the end of the first anchor. I've fixed the code here.

                                  – ChaseMedallion
                                  Oct 16 '13 at 12:16





                                  @AdrianIftode: good call. This was definitely a bug. It makes sense to start the search for the second anchor at startIndex, since that's already past the end of the first anchor. I've fixed the code here.

                                  – ChaseMedallion
                                  Oct 16 '13 at 12:16













                                  InvariantCulture isn't working with Windows Universal Apps. Is there any way to remove it with keeping the functionality of your class? @ChaseMedallion

                                  – Leon
                                  Sep 12 '15 at 17:02





                                  InvariantCulture isn't working with Windows Universal Apps. Is there any way to remove it with keeping the functionality of your class? @ChaseMedallion

                                  – Leon
                                  Sep 12 '15 at 17:02













                                  @Leon: you should be able to rip out all the culture-related stuff and .NET will just use the current culture for the indexOf operation. I'm not familiar with Windows Universal Apps, though, so I can't say for sure.

                                  – ChaseMedallion
                                  Sep 17 '15 at 12:27





                                  @Leon: you should be able to rip out all the culture-related stuff and .NET will just use the current culture for the indexOf operation. I'm not familiar with Windows Universal Apps, though, so I can't say for sure.

                                  – ChaseMedallion
                                  Sep 17 '15 at 12:27











                                  10














                                  Regex is overkill here.



                                  You could use string.Split with the overload that takes a string for the delimiters but that would also be overkill.



                                  Look at Substring and IndexOf - the former to get parts of a string given and index and a length and the second for finding indexed of inner strings/characters.






                                  share|improve this answer



















                                  • 2





                                    It's not overkill... in fact I would say Substring and IndexOf are underkill. I'd say that string.Split is about right. Regex is overkill.

                                    – It'sNotALie.
                                    Jun 22 '13 at 16:22






                                  • 2





                                    The point of it being overkill or under-kill is moot, because the answer fulfills the poster's request of doing it another way than Regex.

                                    – Karl Anderson
                                    Jun 22 '13 at 16:29






                                  • 2





                                    @newStackExchangeInstance: it also fails if there is a " - " before the " key : ". Substring is spot on.

                                    – jmoreno
                                    Jun 22 '13 at 17:16











                                  • It shouldn't if you know how to write regex...

                                    – It'sNotALie.
                                    Jun 22 '13 at 17:16











                                  • @newStackExchangeInstance - I believe he is talking about string.Split.

                                    – Oded
                                    Jun 22 '13 at 17:18
















                                  10














                                  Regex is overkill here.



                                  You could use string.Split with the overload that takes a string for the delimiters but that would also be overkill.



                                  Look at Substring and IndexOf - the former to get parts of a string given and index and a length and the second for finding indexed of inner strings/characters.






                                  share|improve this answer



















                                  • 2





                                    It's not overkill... in fact I would say Substring and IndexOf are underkill. I'd say that string.Split is about right. Regex is overkill.

                                    – It'sNotALie.
                                    Jun 22 '13 at 16:22






                                  • 2





                                    The point of it being overkill or under-kill is moot, because the answer fulfills the poster's request of doing it another way than Regex.

                                    – Karl Anderson
                                    Jun 22 '13 at 16:29






                                  • 2





                                    @newStackExchangeInstance: it also fails if there is a " - " before the " key : ". Substring is spot on.

                                    – jmoreno
                                    Jun 22 '13 at 17:16











                                  • It shouldn't if you know how to write regex...

                                    – It'sNotALie.
                                    Jun 22 '13 at 17:16











                                  • @newStackExchangeInstance - I believe he is talking about string.Split.

                                    – Oded
                                    Jun 22 '13 at 17:18














                                  10












                                  10








                                  10







                                  Regex is overkill here.



                                  You could use string.Split with the overload that takes a string for the delimiters but that would also be overkill.



                                  Look at Substring and IndexOf - the former to get parts of a string given and index and a length and the second for finding indexed of inner strings/characters.






                                  share|improve this answer













                                  Regex is overkill here.



                                  You could use string.Split with the overload that takes a string for the delimiters but that would also be overkill.



                                  Look at Substring and IndexOf - the former to get parts of a string given and index and a length and the second for finding indexed of inner strings/characters.







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Jun 22 '13 at 16:04









                                  OdedOded

                                  409k70743910




                                  409k70743910








                                  • 2





                                    It's not overkill... in fact I would say Substring and IndexOf are underkill. I'd say that string.Split is about right. Regex is overkill.

                                    – It'sNotALie.
                                    Jun 22 '13 at 16:22






                                  • 2





                                    The point of it being overkill or under-kill is moot, because the answer fulfills the poster's request of doing it another way than Regex.

                                    – Karl Anderson
                                    Jun 22 '13 at 16:29






                                  • 2





                                    @newStackExchangeInstance: it also fails if there is a " - " before the " key : ". Substring is spot on.

                                    – jmoreno
                                    Jun 22 '13 at 17:16











                                  • It shouldn't if you know how to write regex...

                                    – It'sNotALie.
                                    Jun 22 '13 at 17:16











                                  • @newStackExchangeInstance - I believe he is talking about string.Split.

                                    – Oded
                                    Jun 22 '13 at 17:18














                                  • 2





                                    It's not overkill... in fact I would say Substring and IndexOf are underkill. I'd say that string.Split is about right. Regex is overkill.

                                    – It'sNotALie.
                                    Jun 22 '13 at 16:22






                                  • 2





                                    The point of it being overkill or under-kill is moot, because the answer fulfills the poster's request of doing it another way than Regex.

                                    – Karl Anderson
                                    Jun 22 '13 at 16:29






                                  • 2





                                    @newStackExchangeInstance: it also fails if there is a " - " before the " key : ". Substring is spot on.

                                    – jmoreno
                                    Jun 22 '13 at 17:16











                                  • It shouldn't if you know how to write regex...

                                    – It'sNotALie.
                                    Jun 22 '13 at 17:16











                                  • @newStackExchangeInstance - I believe he is talking about string.Split.

                                    – Oded
                                    Jun 22 '13 at 17:18








                                  2




                                  2





                                  It's not overkill... in fact I would say Substring and IndexOf are underkill. I'd say that string.Split is about right. Regex is overkill.

                                  – It'sNotALie.
                                  Jun 22 '13 at 16:22





                                  It's not overkill... in fact I would say Substring and IndexOf are underkill. I'd say that string.Split is about right. Regex is overkill.

                                  – It'sNotALie.
                                  Jun 22 '13 at 16:22




                                  2




                                  2





                                  The point of it being overkill or under-kill is moot, because the answer fulfills the poster's request of doing it another way than Regex.

                                  – Karl Anderson
                                  Jun 22 '13 at 16:29





                                  The point of it being overkill or under-kill is moot, because the answer fulfills the poster's request of doing it another way than Regex.

                                  – Karl Anderson
                                  Jun 22 '13 at 16:29




                                  2




                                  2





                                  @newStackExchangeInstance: it also fails if there is a " - " before the " key : ". Substring is spot on.

                                  – jmoreno
                                  Jun 22 '13 at 17:16





                                  @newStackExchangeInstance: it also fails if there is a " - " before the " key : ". Substring is spot on.

                                  – jmoreno
                                  Jun 22 '13 at 17:16













                                  It shouldn't if you know how to write regex...

                                  – It'sNotALie.
                                  Jun 22 '13 at 17:16





                                  It shouldn't if you know how to write regex...

                                  – It'sNotALie.
                                  Jun 22 '13 at 17:16













                                  @newStackExchangeInstance - I believe he is talking about string.Split.

                                  – Oded
                                  Jun 22 '13 at 17:18





                                  @newStackExchangeInstance - I believe he is talking about string.Split.

                                  – Oded
                                  Jun 22 '13 at 17:18











                                  8














                                  Here is the way how i can do that



                                     public string Between(string STR , string FirstString, string LastString)
                                  {
                                  string FinalString;
                                  int Pos1 = STR.IndexOf(FirstString) + FirstString.Length;
                                  int Pos2 = STR.IndexOf(LastString);
                                  FinalString = STR.Substring(Pos1, Pos2 - Pos1);
                                  return FinalString;
                                  }





                                  share|improve this answer




























                                    8














                                    Here is the way how i can do that



                                       public string Between(string STR , string FirstString, string LastString)
                                    {
                                    string FinalString;
                                    int Pos1 = STR.IndexOf(FirstString) + FirstString.Length;
                                    int Pos2 = STR.IndexOf(LastString);
                                    FinalString = STR.Substring(Pos1, Pos2 - Pos1);
                                    return FinalString;
                                    }





                                    share|improve this answer


























                                      8












                                      8








                                      8







                                      Here is the way how i can do that



                                         public string Between(string STR , string FirstString, string LastString)
                                      {
                                      string FinalString;
                                      int Pos1 = STR.IndexOf(FirstString) + FirstString.Length;
                                      int Pos2 = STR.IndexOf(LastString);
                                      FinalString = STR.Substring(Pos1, Pos2 - Pos1);
                                      return FinalString;
                                      }





                                      share|improve this answer













                                      Here is the way how i can do that



                                         public string Between(string STR , string FirstString, string LastString)
                                      {
                                      string FinalString;
                                      int Pos1 = STR.IndexOf(FirstString) + FirstString.Length;
                                      int Pos2 = STR.IndexOf(LastString);
                                      FinalString = STR.Substring(Pos1, Pos2 - Pos1);
                                      return FinalString;
                                      }






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Oct 21 '14 at 6:20









                                      Vijay Singh RanaVijay Singh Rana

                                      645828




                                      645828























                                          7














                                          I think this works:



                                             static void Main(string args)
                                          {
                                          String text = "One=1,Two=2,ThreeFour=34";

                                          Console.WriteLine(betweenStrings(text, "One=", ",")); // 1
                                          Console.WriteLine(betweenStrings(text, "Two=", ",")); // 2
                                          Console.WriteLine(betweenStrings(text, "ThreeFour=", "")); // 34

                                          Console.ReadKey();

                                          }

                                          public static String betweenStrings(String text, String start, String end)
                                          {
                                          int p1 = text.IndexOf(start) + start.Length;
                                          int p2 = text.IndexOf(end, p1);

                                          if (end == "") return (text.Substring(p1));
                                          else return text.Substring(p1, p2 - p1);
                                          }





                                          share|improve this answer
























                                          • Great solution. Thanks!

                                            – arcee123
                                            Aug 31 '18 at 0:53
















                                          7














                                          I think this works:



                                             static void Main(string args)
                                          {
                                          String text = "One=1,Two=2,ThreeFour=34";

                                          Console.WriteLine(betweenStrings(text, "One=", ",")); // 1
                                          Console.WriteLine(betweenStrings(text, "Two=", ",")); // 2
                                          Console.WriteLine(betweenStrings(text, "ThreeFour=", "")); // 34

                                          Console.ReadKey();

                                          }

                                          public static String betweenStrings(String text, String start, String end)
                                          {
                                          int p1 = text.IndexOf(start) + start.Length;
                                          int p2 = text.IndexOf(end, p1);

                                          if (end == "") return (text.Substring(p1));
                                          else return text.Substring(p1, p2 - p1);
                                          }





                                          share|improve this answer
























                                          • Great solution. Thanks!

                                            – arcee123
                                            Aug 31 '18 at 0:53














                                          7












                                          7








                                          7







                                          I think this works:



                                             static void Main(string args)
                                          {
                                          String text = "One=1,Two=2,ThreeFour=34";

                                          Console.WriteLine(betweenStrings(text, "One=", ",")); // 1
                                          Console.WriteLine(betweenStrings(text, "Two=", ",")); // 2
                                          Console.WriteLine(betweenStrings(text, "ThreeFour=", "")); // 34

                                          Console.ReadKey();

                                          }

                                          public static String betweenStrings(String text, String start, String end)
                                          {
                                          int p1 = text.IndexOf(start) + start.Length;
                                          int p2 = text.IndexOf(end, p1);

                                          if (end == "") return (text.Substring(p1));
                                          else return text.Substring(p1, p2 - p1);
                                          }





                                          share|improve this answer













                                          I think this works:



                                             static void Main(string args)
                                          {
                                          String text = "One=1,Two=2,ThreeFour=34";

                                          Console.WriteLine(betweenStrings(text, "One=", ",")); // 1
                                          Console.WriteLine(betweenStrings(text, "Two=", ",")); // 2
                                          Console.WriteLine(betweenStrings(text, "ThreeFour=", "")); // 34

                                          Console.ReadKey();

                                          }

                                          public static String betweenStrings(String text, String start, String end)
                                          {
                                          int p1 = text.IndexOf(start) + start.Length;
                                          int p2 = text.IndexOf(end, p1);

                                          if (end == "") return (text.Substring(p1));
                                          else return text.Substring(p1, p2 - p1);
                                          }






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Oct 25 '17 at 19:02









                                          fr0gafr0ga

                                          10514




                                          10514













                                          • Great solution. Thanks!

                                            – arcee123
                                            Aug 31 '18 at 0:53



















                                          • Great solution. Thanks!

                                            – arcee123
                                            Aug 31 '18 at 0:53

















                                          Great solution. Thanks!

                                          – arcee123
                                          Aug 31 '18 at 0:53





                                          Great solution. Thanks!

                                          – arcee123
                                          Aug 31 '18 at 0:53











                                          5














                                           string str="super exemple of string key : text I want to keep - end of my string";
                                          int startIndex = str.IndexOf("key") + "key".Length;
                                          int endIndex = str.IndexOf("-");
                                          string newString = str.Substring(startIndex, endIndex - startIndex);





                                          share|improve this answer



















                                          • 1





                                            Your code would result in the colon being returned at the beginning of the newString.

                                            – tsells
                                            Jun 23 '13 at 2:18
















                                          5














                                           string str="super exemple of string key : text I want to keep - end of my string";
                                          int startIndex = str.IndexOf("key") + "key".Length;
                                          int endIndex = str.IndexOf("-");
                                          string newString = str.Substring(startIndex, endIndex - startIndex);





                                          share|improve this answer



















                                          • 1





                                            Your code would result in the colon being returned at the beginning of the newString.

                                            – tsells
                                            Jun 23 '13 at 2:18














                                          5












                                          5








                                          5







                                           string str="super exemple of string key : text I want to keep - end of my string";
                                          int startIndex = str.IndexOf("key") + "key".Length;
                                          int endIndex = str.IndexOf("-");
                                          string newString = str.Substring(startIndex, endIndex - startIndex);





                                          share|improve this answer













                                           string str="super exemple of string key : text I want to keep - end of my string";
                                          int startIndex = str.IndexOf("key") + "key".Length;
                                          int endIndex = str.IndexOf("-");
                                          string newString = str.Substring(startIndex, endIndex - startIndex);






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Jun 22 '13 at 21:01









                                          Dejan CievDejan Ciev

                                          1244




                                          1244








                                          • 1





                                            Your code would result in the colon being returned at the beginning of the newString.

                                            – tsells
                                            Jun 23 '13 at 2:18














                                          • 1





                                            Your code would result in the colon being returned at the beginning of the newString.

                                            – tsells
                                            Jun 23 '13 at 2:18








                                          1




                                          1





                                          Your code would result in the colon being returned at the beginning of the newString.

                                          – tsells
                                          Jun 23 '13 at 2:18





                                          Your code would result in the colon being returned at the beginning of the newString.

                                          – tsells
                                          Jun 23 '13 at 2:18











                                          5














                                          or, with a regex.



                                          using System.Text.RegularExpressions;

                                          ...

                                          var value =
                                          Regex.Match(
                                          "super exemple of string key : text I want to keep - end of my string",
                                          "key : (.*) - ")
                                          .Groups[1].Value;


                                          with a running example.



                                          You can decide if its overkill.



                                          or



                                          as an under validated extension method



                                          using System.Text.RegularExpressions;

                                          public class Test
                                          {
                                          public static void Main()
                                          {
                                          var value =
                                          "super exemple of string key : text I want to keep - end of my string"
                                          .Between(
                                          "key : ",
                                          " - ");

                                          Console.WriteLine(value);
                                          }
                                          }

                                          public static class Ext
                                          {
                                          static string Between(this string source, string left, string right)
                                          {
                                          return Regex.Match(
                                          source,
                                          string.Format("{0}(.*){1}", left, right))
                                          .Groups[1].Value;
                                          }
                                          }





                                          share|improve this answer






























                                            5














                                            or, with a regex.



                                            using System.Text.RegularExpressions;

                                            ...

                                            var value =
                                            Regex.Match(
                                            "super exemple of string key : text I want to keep - end of my string",
                                            "key : (.*) - ")
                                            .Groups[1].Value;


                                            with a running example.



                                            You can decide if its overkill.



                                            or



                                            as an under validated extension method



                                            using System.Text.RegularExpressions;

                                            public class Test
                                            {
                                            public static void Main()
                                            {
                                            var value =
                                            "super exemple of string key : text I want to keep - end of my string"
                                            .Between(
                                            "key : ",
                                            " - ");

                                            Console.WriteLine(value);
                                            }
                                            }

                                            public static class Ext
                                            {
                                            static string Between(this string source, string left, string right)
                                            {
                                            return Regex.Match(
                                            source,
                                            string.Format("{0}(.*){1}", left, right))
                                            .Groups[1].Value;
                                            }
                                            }





                                            share|improve this answer




























                                              5












                                              5








                                              5







                                              or, with a regex.



                                              using System.Text.RegularExpressions;

                                              ...

                                              var value =
                                              Regex.Match(
                                              "super exemple of string key : text I want to keep - end of my string",
                                              "key : (.*) - ")
                                              .Groups[1].Value;


                                              with a running example.



                                              You can decide if its overkill.



                                              or



                                              as an under validated extension method



                                              using System.Text.RegularExpressions;

                                              public class Test
                                              {
                                              public static void Main()
                                              {
                                              var value =
                                              "super exemple of string key : text I want to keep - end of my string"
                                              .Between(
                                              "key : ",
                                              " - ");

                                              Console.WriteLine(value);
                                              }
                                              }

                                              public static class Ext
                                              {
                                              static string Between(this string source, string left, string right)
                                              {
                                              return Regex.Match(
                                              source,
                                              string.Format("{0}(.*){1}", left, right))
                                              .Groups[1].Value;
                                              }
                                              }





                                              share|improve this answer















                                              or, with a regex.



                                              using System.Text.RegularExpressions;

                                              ...

                                              var value =
                                              Regex.Match(
                                              "super exemple of string key : text I want to keep - end of my string",
                                              "key : (.*) - ")
                                              .Groups[1].Value;


                                              with a running example.



                                              You can decide if its overkill.



                                              or



                                              as an under validated extension method



                                              using System.Text.RegularExpressions;

                                              public class Test
                                              {
                                              public static void Main()
                                              {
                                              var value =
                                              "super exemple of string key : text I want to keep - end of my string"
                                              .Between(
                                              "key : ",
                                              " - ");

                                              Console.WriteLine(value);
                                              }
                                              }

                                              public static class Ext
                                              {
                                              static string Between(this string source, string left, string right)
                                              {
                                              return Regex.Match(
                                              source,
                                              string.Format("{0}(.*){1}", left, right))
                                              .Groups[1].Value;
                                              }
                                              }






                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Feb 25 '15 at 16:10

























                                              answered Feb 25 '15 at 15:54









                                              JodrellJodrell

                                              26.6k35895




                                              26.6k35895























                                                  4














                                                  A working LINQ solution:



                                                  string str = "super exemple of string key : text I want to keep - end of my string";
                                                  string res = new string(str.SkipWhile(c => c != ':')
                                                  .Skip(1)
                                                  .TakeWhile(c => c != '-')
                                                  .ToArray()).Trim();
                                                  Console.WriteLine(res); // text I want to keep





                                                  share|improve this answer
























                                                  • super easy solution.thank you.

                                                    – Erdinç
                                                    Nov 12 '16 at 18:59













                                                  • Does this works for single-character placeholders only?

                                                    – beppe9000
                                                    Oct 6 '17 at 21:50
















                                                  4














                                                  A working LINQ solution:



                                                  string str = "super exemple of string key : text I want to keep - end of my string";
                                                  string res = new string(str.SkipWhile(c => c != ':')
                                                  .Skip(1)
                                                  .TakeWhile(c => c != '-')
                                                  .ToArray()).Trim();
                                                  Console.WriteLine(res); // text I want to keep





                                                  share|improve this answer
























                                                  • super easy solution.thank you.

                                                    – Erdinç
                                                    Nov 12 '16 at 18:59













                                                  • Does this works for single-character placeholders only?

                                                    – beppe9000
                                                    Oct 6 '17 at 21:50














                                                  4












                                                  4








                                                  4







                                                  A working LINQ solution:



                                                  string str = "super exemple of string key : text I want to keep - end of my string";
                                                  string res = new string(str.SkipWhile(c => c != ':')
                                                  .Skip(1)
                                                  .TakeWhile(c => c != '-')
                                                  .ToArray()).Trim();
                                                  Console.WriteLine(res); // text I want to keep





                                                  share|improve this answer













                                                  A working LINQ solution:



                                                  string str = "super exemple of string key : text I want to keep - end of my string";
                                                  string res = new string(str.SkipWhile(c => c != ':')
                                                  .Skip(1)
                                                  .TakeWhile(c => c != '-')
                                                  .ToArray()).Trim();
                                                  Console.WriteLine(res); // text I want to keep






                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Feb 25 '15 at 15:42









                                                  w.bw.b

                                                  8,87742038




                                                  8,87742038













                                                  • super easy solution.thank you.

                                                    – Erdinç
                                                    Nov 12 '16 at 18:59













                                                  • Does this works for single-character placeholders only?

                                                    – beppe9000
                                                    Oct 6 '17 at 21:50



















                                                  • super easy solution.thank you.

                                                    – Erdinç
                                                    Nov 12 '16 at 18:59













                                                  • Does this works for single-character placeholders only?

                                                    – beppe9000
                                                    Oct 6 '17 at 21:50

















                                                  super easy solution.thank you.

                                                  – Erdinç
                                                  Nov 12 '16 at 18:59







                                                  super easy solution.thank you.

                                                  – Erdinç
                                                  Nov 12 '16 at 18:59















                                                  Does this works for single-character placeholders only?

                                                  – beppe9000
                                                  Oct 6 '17 at 21:50





                                                  Does this works for single-character placeholders only?

                                                  – beppe9000
                                                  Oct 6 '17 at 21:50











                                                  3














                                                  Since the : and the - are unique you could use:



                                                  string input;
                                                  string output;
                                                  input = "super example of string key : text I want to keep - end of my string";
                                                  output = input.Split(new char { ':', '-' })[1];





                                                  share|improve this answer


























                                                  • This answer doesn't add anything meaningful to the already big amount of existing answers.

                                                    – Mephy
                                                    Apr 8 '15 at 19:59
















                                                  3














                                                  Since the : and the - are unique you could use:



                                                  string input;
                                                  string output;
                                                  input = "super example of string key : text I want to keep - end of my string";
                                                  output = input.Split(new char { ':', '-' })[1];





                                                  share|improve this answer


























                                                  • This answer doesn't add anything meaningful to the already big amount of existing answers.

                                                    – Mephy
                                                    Apr 8 '15 at 19:59














                                                  3












                                                  3








                                                  3







                                                  Since the : and the - are unique you could use:



                                                  string input;
                                                  string output;
                                                  input = "super example of string key : text I want to keep - end of my string";
                                                  output = input.Split(new char { ':', '-' })[1];





                                                  share|improve this answer















                                                  Since the : and the - are unique you could use:



                                                  string input;
                                                  string output;
                                                  input = "super example of string key : text I want to keep - end of my string";
                                                  output = input.Split(new char { ':', '-' })[1];






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Apr 8 '15 at 20:28









                                                  michaelpri

                                                  2,66132237




                                                  2,66132237










                                                  answered Apr 8 '15 at 19:53









                                                  Michael FreemanMichael Freeman

                                                  312




                                                  312













                                                  • This answer doesn't add anything meaningful to the already big amount of existing answers.

                                                    – Mephy
                                                    Apr 8 '15 at 19:59



















                                                  • This answer doesn't add anything meaningful to the already big amount of existing answers.

                                                    – Mephy
                                                    Apr 8 '15 at 19:59

















                                                  This answer doesn't add anything meaningful to the already big amount of existing answers.

                                                  – Mephy
                                                  Apr 8 '15 at 19:59





                                                  This answer doesn't add anything meaningful to the already big amount of existing answers.

                                                  – Mephy
                                                  Apr 8 '15 at 19:59











                                                  2














                                                  You can use the extension method below:



                                                  public static string GetStringBetween(this string token, string first, string second)
                                                  {
                                                  if (!token.Contains(first)) return "";

                                                  var afterFirst = token.Split(new { first }, StringSplitOptions.None)[1];

                                                  if (!afterFirst.Contains(second)) return "";

                                                  var result = afterFirst.Split(new { second }, StringSplitOptions.None)[0];

                                                  return result;
                                                  }


                                                  Usage is:



                                                  var token = "super exemple of string key : text I want to keep - end of my string";
                                                  var keyValue = token.GetStringBetween("key : ", " - ");





                                                  share|improve this answer




























                                                    2














                                                    You can use the extension method below:



                                                    public static string GetStringBetween(this string token, string first, string second)
                                                    {
                                                    if (!token.Contains(first)) return "";

                                                    var afterFirst = token.Split(new { first }, StringSplitOptions.None)[1];

                                                    if (!afterFirst.Contains(second)) return "";

                                                    var result = afterFirst.Split(new { second }, StringSplitOptions.None)[0];

                                                    return result;
                                                    }


                                                    Usage is:



                                                    var token = "super exemple of string key : text I want to keep - end of my string";
                                                    var keyValue = token.GetStringBetween("key : ", " - ");





                                                    share|improve this answer


























                                                      2












                                                      2








                                                      2







                                                      You can use the extension method below:



                                                      public static string GetStringBetween(this string token, string first, string second)
                                                      {
                                                      if (!token.Contains(first)) return "";

                                                      var afterFirst = token.Split(new { first }, StringSplitOptions.None)[1];

                                                      if (!afterFirst.Contains(second)) return "";

                                                      var result = afterFirst.Split(new { second }, StringSplitOptions.None)[0];

                                                      return result;
                                                      }


                                                      Usage is:



                                                      var token = "super exemple of string key : text I want to keep - end of my string";
                                                      var keyValue = token.GetStringBetween("key : ", " - ");





                                                      share|improve this answer













                                                      You can use the extension method below:



                                                      public static string GetStringBetween(this string token, string first, string second)
                                                      {
                                                      if (!token.Contains(first)) return "";

                                                      var afterFirst = token.Split(new { first }, StringSplitOptions.None)[1];

                                                      if (!afterFirst.Contains(second)) return "";

                                                      var result = afterFirst.Split(new { second }, StringSplitOptions.None)[0];

                                                      return result;
                                                      }


                                                      Usage is:



                                                      var token = "super exemple of string key : text I want to keep - end of my string";
                                                      var keyValue = token.GetStringBetween("key : ", " - ");






                                                      share|improve this answer












                                                      share|improve this answer



                                                      share|improve this answer










                                                      answered Aug 5 '16 at 17:07









                                                      serefbilgeserefbilge

                                                      97132149




                                                      97132149























                                                          1














                                                          You already have some good answers and I realize the code I am providing is far from the most efficient and clean. However, I thought it might be useful for educational purposes. We can use pre-built classes and libraries all day long. But without understanding the inner-workings, we are simply mimicking and repeating and will never learn anything. This code works and is more basic or "virgin" than some of the others:



                                                          char startDelimiter = ':';
                                                          char endDelimiter = '-';

                                                          Boolean collect = false;

                                                          string parsedString = "";

                                                          foreach (char c in originalString)
                                                          {
                                                          if (c == startDelimiter)
                                                          collect = true;

                                                          if (c == endDelimiter)
                                                          collect = false;

                                                          if (collect == true && c != startDelimiter)
                                                          parsedString += c;
                                                          }


                                                          You end up with your desired string assigned to the parsedString variable. Keep in mind that it will also capture proceeding and preceding spaces. Remember that a string is simply an array of characters that can be manipulated like other arrays with indices etc.



                                                          Take care.






                                                          share|improve this answer
























                                                          • This is the best algorithm although the worst in string creation. All the answers provided that are not regex-only are trigger-happy at creating strings but this one is the worst of all in that sense. If you had just captured the beginning an end of the string to capture and used ''string.Substring'' to extract it, it would be perfect.

                                                            – Paulo Morgado
                                                            Jun 23 '13 at 0:12













                                                          • I agree. As I mentioned, it is far from efficient. I wouldn't recommend using this algorithm. It is simply ""dumbing it down" so he can understand strings at a lower level. If he simply wants to get the job done, he already had answers that would achieve that.

                                                            – flyNflip
                                                            Jun 24 '13 at 16:00











                                                          • I understood that. I was just pointing out its strong and week points. Although, to answer the original question it requires a bit more as it need to match a string boundaries and not just character boundaries. But the idea is just the same.

                                                            – Paulo Morgado
                                                            Jun 24 '13 at 20:53











                                                          • Absolutely. You are right on target.

                                                            – flyNflip
                                                            Jun 24 '13 at 21:24
















                                                          1














                                                          You already have some good answers and I realize the code I am providing is far from the most efficient and clean. However, I thought it might be useful for educational purposes. We can use pre-built classes and libraries all day long. But without understanding the inner-workings, we are simply mimicking and repeating and will never learn anything. This code works and is more basic or "virgin" than some of the others:



                                                          char startDelimiter = ':';
                                                          char endDelimiter = '-';

                                                          Boolean collect = false;

                                                          string parsedString = "";

                                                          foreach (char c in originalString)
                                                          {
                                                          if (c == startDelimiter)
                                                          collect = true;

                                                          if (c == endDelimiter)
                                                          collect = false;

                                                          if (collect == true && c != startDelimiter)
                                                          parsedString += c;
                                                          }


                                                          You end up with your desired string assigned to the parsedString variable. Keep in mind that it will also capture proceeding and preceding spaces. Remember that a string is simply an array of characters that can be manipulated like other arrays with indices etc.



                                                          Take care.






                                                          share|improve this answer
























                                                          • This is the best algorithm although the worst in string creation. All the answers provided that are not regex-only are trigger-happy at creating strings but this one is the worst of all in that sense. If you had just captured the beginning an end of the string to capture and used ''string.Substring'' to extract it, it would be perfect.

                                                            – Paulo Morgado
                                                            Jun 23 '13 at 0:12













                                                          • I agree. As I mentioned, it is far from efficient. I wouldn't recommend using this algorithm. It is simply ""dumbing it down" so he can understand strings at a lower level. If he simply wants to get the job done, he already had answers that would achieve that.

                                                            – flyNflip
                                                            Jun 24 '13 at 16:00











                                                          • I understood that. I was just pointing out its strong and week points. Although, to answer the original question it requires a bit more as it need to match a string boundaries and not just character boundaries. But the idea is just the same.

                                                            – Paulo Morgado
                                                            Jun 24 '13 at 20:53











                                                          • Absolutely. You are right on target.

                                                            – flyNflip
                                                            Jun 24 '13 at 21:24














                                                          1












                                                          1








                                                          1







                                                          You already have some good answers and I realize the code I am providing is far from the most efficient and clean. However, I thought it might be useful for educational purposes. We can use pre-built classes and libraries all day long. But without understanding the inner-workings, we are simply mimicking and repeating and will never learn anything. This code works and is more basic or "virgin" than some of the others:



                                                          char startDelimiter = ':';
                                                          char endDelimiter = '-';

                                                          Boolean collect = false;

                                                          string parsedString = "";

                                                          foreach (char c in originalString)
                                                          {
                                                          if (c == startDelimiter)
                                                          collect = true;

                                                          if (c == endDelimiter)
                                                          collect = false;

                                                          if (collect == true && c != startDelimiter)
                                                          parsedString += c;
                                                          }


                                                          You end up with your desired string assigned to the parsedString variable. Keep in mind that it will also capture proceeding and preceding spaces. Remember that a string is simply an array of characters that can be manipulated like other arrays with indices etc.



                                                          Take care.






                                                          share|improve this answer













                                                          You already have some good answers and I realize the code I am providing is far from the most efficient and clean. However, I thought it might be useful for educational purposes. We can use pre-built classes and libraries all day long. But without understanding the inner-workings, we are simply mimicking and repeating and will never learn anything. This code works and is more basic or "virgin" than some of the others:



                                                          char startDelimiter = ':';
                                                          char endDelimiter = '-';

                                                          Boolean collect = false;

                                                          string parsedString = "";

                                                          foreach (char c in originalString)
                                                          {
                                                          if (c == startDelimiter)
                                                          collect = true;

                                                          if (c == endDelimiter)
                                                          collect = false;

                                                          if (collect == true && c != startDelimiter)
                                                          parsedString += c;
                                                          }


                                                          You end up with your desired string assigned to the parsedString variable. Keep in mind that it will also capture proceeding and preceding spaces. Remember that a string is simply an array of characters that can be manipulated like other arrays with indices etc.



                                                          Take care.







                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Jun 22 '13 at 16:41









                                                          flyNflipflyNflip

                                                          2381314




                                                          2381314













                                                          • This is the best algorithm although the worst in string creation. All the answers provided that are not regex-only are trigger-happy at creating strings but this one is the worst of all in that sense. If you had just captured the beginning an end of the string to capture and used ''string.Substring'' to extract it, it would be perfect.

                                                            – Paulo Morgado
                                                            Jun 23 '13 at 0:12













                                                          • I agree. As I mentioned, it is far from efficient. I wouldn't recommend using this algorithm. It is simply ""dumbing it down" so he can understand strings at a lower level. If he simply wants to get the job done, he already had answers that would achieve that.

                                                            – flyNflip
                                                            Jun 24 '13 at 16:00











                                                          • I understood that. I was just pointing out its strong and week points. Although, to answer the original question it requires a bit more as it need to match a string boundaries and not just character boundaries. But the idea is just the same.

                                                            – Paulo Morgado
                                                            Jun 24 '13 at 20:53











                                                          • Absolutely. You are right on target.

                                                            – flyNflip
                                                            Jun 24 '13 at 21:24



















                                                          • This is the best algorithm although the worst in string creation. All the answers provided that are not regex-only are trigger-happy at creating strings but this one is the worst of all in that sense. If you had just captured the beginning an end of the string to capture and used ''string.Substring'' to extract it, it would be perfect.

                                                            – Paulo Morgado
                                                            Jun 23 '13 at 0:12













                                                          • I agree. As I mentioned, it is far from efficient. I wouldn't recommend using this algorithm. It is simply ""dumbing it down" so he can understand strings at a lower level. If he simply wants to get the job done, he already had answers that would achieve that.

                                                            – flyNflip
                                                            Jun 24 '13 at 16:00











                                                          • I understood that. I was just pointing out its strong and week points. Although, to answer the original question it requires a bit more as it need to match a string boundaries and not just character boundaries. But the idea is just the same.

                                                            – Paulo Morgado
                                                            Jun 24 '13 at 20:53











                                                          • Absolutely. You are right on target.

                                                            – flyNflip
                                                            Jun 24 '13 at 21:24

















                                                          This is the best algorithm although the worst in string creation. All the answers provided that are not regex-only are trigger-happy at creating strings but this one is the worst of all in that sense. If you had just captured the beginning an end of the string to capture and used ''string.Substring'' to extract it, it would be perfect.

                                                          – Paulo Morgado
                                                          Jun 23 '13 at 0:12







                                                          This is the best algorithm although the worst in string creation. All the answers provided that are not regex-only are trigger-happy at creating strings but this one is the worst of all in that sense. If you had just captured the beginning an end of the string to capture and used ''string.Substring'' to extract it, it would be perfect.

                                                          – Paulo Morgado
                                                          Jun 23 '13 at 0:12















                                                          I agree. As I mentioned, it is far from efficient. I wouldn't recommend using this algorithm. It is simply ""dumbing it down" so he can understand strings at a lower level. If he simply wants to get the job done, he already had answers that would achieve that.

                                                          – flyNflip
                                                          Jun 24 '13 at 16:00





                                                          I agree. As I mentioned, it is far from efficient. I wouldn't recommend using this algorithm. It is simply ""dumbing it down" so he can understand strings at a lower level. If he simply wants to get the job done, he already had answers that would achieve that.

                                                          – flyNflip
                                                          Jun 24 '13 at 16:00













                                                          I understood that. I was just pointing out its strong and week points. Although, to answer the original question it requires a bit more as it need to match a string boundaries and not just character boundaries. But the idea is just the same.

                                                          – Paulo Morgado
                                                          Jun 24 '13 at 20:53





                                                          I understood that. I was just pointing out its strong and week points. Although, to answer the original question it requires a bit more as it need to match a string boundaries and not just character boundaries. But the idea is just the same.

                                                          – Paulo Morgado
                                                          Jun 24 '13 at 20:53













                                                          Absolutely. You are right on target.

                                                          – flyNflip
                                                          Jun 24 '13 at 21:24





                                                          Absolutely. You are right on target.

                                                          – flyNflip
                                                          Jun 24 '13 at 21:24











                                                          1














                                                          var matches = Regex.Matches(input, @"(?<=key :)(.+?)(?=-)");


                                                          This returns only the value(s) between "key :" and the following occurance of "-"






                                                          share|improve this answer




























                                                            1














                                                            var matches = Regex.Matches(input, @"(?<=key :)(.+?)(?=-)");


                                                            This returns only the value(s) between "key :" and the following occurance of "-"






                                                            share|improve this answer


























                                                              1












                                                              1








                                                              1







                                                              var matches = Regex.Matches(input, @"(?<=key :)(.+?)(?=-)");


                                                              This returns only the value(s) between "key :" and the following occurance of "-"






                                                              share|improve this answer













                                                              var matches = Regex.Matches(input, @"(?<=key :)(.+?)(?=-)");


                                                              This returns only the value(s) between "key :" and the following occurance of "-"







                                                              share|improve this answer












                                                              share|improve this answer



                                                              share|improve this answer










                                                              answered Dec 29 '17 at 13:56









                                                              fboethiusfboethius

                                                              184




                                                              184























                                                                  0














                                                                  As I always say nothing is impossible:



                                                                  string value =  "super exemple of string key : text I want to keep - end of my string";
                                                                  Regex regex = new Regex(@"(key : (.*?) _ )");
                                                                  Match match = regex.Match(value);
                                                                  if (match.Success)
                                                                  {
                                                                  Messagebox.Show(match.Value);
                                                                  }



                                                                  Remeber that should add reference of System.Text.RegularExpressions




                                                                  Hope That I Helped.






                                                                  share|improve this answer




























                                                                    0














                                                                    As I always say nothing is impossible:



                                                                    string value =  "super exemple of string key : text I want to keep - end of my string";
                                                                    Regex regex = new Regex(@"(key : (.*?) _ )");
                                                                    Match match = regex.Match(value);
                                                                    if (match.Success)
                                                                    {
                                                                    Messagebox.Show(match.Value);
                                                                    }



                                                                    Remeber that should add reference of System.Text.RegularExpressions




                                                                    Hope That I Helped.






                                                                    share|improve this answer


























                                                                      0












                                                                      0








                                                                      0







                                                                      As I always say nothing is impossible:



                                                                      string value =  "super exemple of string key : text I want to keep - end of my string";
                                                                      Regex regex = new Regex(@"(key : (.*?) _ )");
                                                                      Match match = regex.Match(value);
                                                                      if (match.Success)
                                                                      {
                                                                      Messagebox.Show(match.Value);
                                                                      }



                                                                      Remeber that should add reference of System.Text.RegularExpressions




                                                                      Hope That I Helped.






                                                                      share|improve this answer













                                                                      As I always say nothing is impossible:



                                                                      string value =  "super exemple of string key : text I want to keep - end of my string";
                                                                      Regex regex = new Regex(@"(key : (.*?) _ )");
                                                                      Match match = regex.Match(value);
                                                                      if (match.Success)
                                                                      {
                                                                      Messagebox.Show(match.Value);
                                                                      }



                                                                      Remeber that should add reference of System.Text.RegularExpressions




                                                                      Hope That I Helped.







                                                                      share|improve this answer












                                                                      share|improve this answer



                                                                      share|improve this answer










                                                                      answered Feb 25 '15 at 15:25









                                                                      Ahmed AlaaAhmed Alaa

                                                                      154111




                                                                      154111























                                                                          0














                                                                          If you are looking for a 1 line solution, this is it:



                                                                          s.Substring(s.IndexOf("eT") + "eT".Length).Split("97".ToCharArray()).First()


                                                                          The whole 1 line solution, with System.Linq:



                                                                          using System;
                                                                          using System.Linq;

                                                                          class OneLiner
                                                                          {
                                                                          static void Main()
                                                                          {
                                                                          string s = "TextHereTisImortant973End"; //Between "eT" and "97"
                                                                          Console.WriteLine(s.Substring(s.IndexOf("eT") + "eT".Length)
                                                                          .Split("97".ToCharArray()).First());
                                                                          }
                                                                          }





                                                                          share|improve this answer






























                                                                            0














                                                                            If you are looking for a 1 line solution, this is it:



                                                                            s.Substring(s.IndexOf("eT") + "eT".Length).Split("97".ToCharArray()).First()


                                                                            The whole 1 line solution, with System.Linq:



                                                                            using System;
                                                                            using System.Linq;

                                                                            class OneLiner
                                                                            {
                                                                            static void Main()
                                                                            {
                                                                            string s = "TextHereTisImortant973End"; //Between "eT" and "97"
                                                                            Console.WriteLine(s.Substring(s.IndexOf("eT") + "eT".Length)
                                                                            .Split("97".ToCharArray()).First());
                                                                            }
                                                                            }





                                                                            share|improve this answer




























                                                                              0












                                                                              0








                                                                              0







                                                                              If you are looking for a 1 line solution, this is it:



                                                                              s.Substring(s.IndexOf("eT") + "eT".Length).Split("97".ToCharArray()).First()


                                                                              The whole 1 line solution, with System.Linq:



                                                                              using System;
                                                                              using System.Linq;

                                                                              class OneLiner
                                                                              {
                                                                              static void Main()
                                                                              {
                                                                              string s = "TextHereTisImortant973End"; //Between "eT" and "97"
                                                                              Console.WriteLine(s.Substring(s.IndexOf("eT") + "eT".Length)
                                                                              .Split("97".ToCharArray()).First());
                                                                              }
                                                                              }





                                                                              share|improve this answer















                                                                              If you are looking for a 1 line solution, this is it:



                                                                              s.Substring(s.IndexOf("eT") + "eT".Length).Split("97".ToCharArray()).First()


                                                                              The whole 1 line solution, with System.Linq:



                                                                              using System;
                                                                              using System.Linq;

                                                                              class OneLiner
                                                                              {
                                                                              static void Main()
                                                                              {
                                                                              string s = "TextHereTisImortant973End"; //Between "eT" and "97"
                                                                              Console.WriteLine(s.Substring(s.IndexOf("eT") + "eT".Length)
                                                                              .Split("97".ToCharArray()).First());
                                                                              }
                                                                              }






                                                                              share|improve this answer














                                                                              share|improve this answer



                                                                              share|improve this answer








                                                                              edited Oct 24 '18 at 18:10

























                                                                              answered Oct 24 '18 at 18:05









                                                                              VityataVityata

                                                                              31.2k72252




                                                                              31.2k72252






























                                                                                  draft saved

                                                                                  draft discarded




















































                                                                                  Thanks for contributing an answer to Stack Overflow!


                                                                                  • Please be sure to answer the question. Provide details and share your research!

                                                                                  But avoid



                                                                                  • Asking for help, clarification, or responding to other answers.

                                                                                  • Making statements based on opinion; back them up with references or personal experience.


                                                                                  To learn more, see our tips on writing great answers.




                                                                                  draft saved


                                                                                  draft discarded














                                                                                  StackExchange.ready(
                                                                                  function () {
                                                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f17252615%2fget-string-between-two-strings-in-a-string%23new-answer', 'question_page');
                                                                                  }
                                                                                  );

                                                                                  Post as a guest















                                                                                  Required, but never shown





















































                                                                                  Required, but never shown














                                                                                  Required, but never shown












                                                                                  Required, but never shown







                                                                                  Required, but never shown

































                                                                                  Required, but never shown














                                                                                  Required, but never shown












                                                                                  Required, but never shown







                                                                                  Required, but never shown







                                                                                  這個網誌中的熱門文章

                                                                                  Academy of Television Arts & Sciences

                                                                                  L'Équipe

                                                                                  1995 France bombings