Get a row between two lines in a row

I have a line like:

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

I want to just save the line that is between "key : " and " - " . How can i do this? Should I use regex or can I do it differently?

+88
string c # regex
Jun 22 '13 at 16:00
source share
18 answers

Perhaps a good way is to just cut the 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); 
+139
Jun 22 '13 at 16:06 on
source share
 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 only with string operations

 var start = input.IndexOf("key : ") + 6; var match2 = input.Substring(start, input.IndexOf("-") - start); 
+32
Jun 22 '13 at 16:03
source share

You can do it without regex

  input.Split(new string[] {"key :"},StringSplitOptions.None)[1] .Split('-')[0] .Trim(); 
+26
Jun 22 '13 at 16:06 on
source share

Depending on how robust / flexible you want your implementation to be, this may be a little more complicated. Here's the implementation I'm using:

 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 " 
+13
Jun 22 '13 at 17:59
source share

Here is how i can do it

  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; } 
+12
Oct 21 '14 at 6:20
source share

Regex overflows here.

You can use string.Split with an overload that takes string[] for delimiters, but that would also be redundant.

Take a look at Substring and IndexOf - the first to get the parts of the string indicated by both the index and the length, and the second to search for indexed internal strings / characters.

+10
Jun 22 '13 at 16:04 on
source share

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); } 
+9
Oct. 25 '17 at 19:02
source share

LINQ working 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 
+6
Feb 25 '15 at 15:42
source share
  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); 
+5
Jun 22 '13 at 21:01
source share

or, with a regular expression.

 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 an example.

You can decide if it can be brute force.

or

as a proven 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; } } 
+5
Feb 25 '15 at 15:54
source share

Since : and - unique, you can 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]; 
+4
Apr 08 '15 at 19:53
source share
 var matches = Regex.Matches(input, @"(?<=key :)(.+?)(?=-)"); 

This returns only the values ​​(s) between the "key" and the following case "-"

+3
Dec 29 '17 at 13:56 on
source share

I used a code snippet from Vijay Singh Rana, which basically does the job. But this causes problems if firstString already contains lastString . I wanted to extract access_token from JSON response (JSON parser not loaded). My firstString was \"access_token\": \" , and my lastString was \" . I ended up with a little modification

 string Between(string str, string firstString, string lastString) { int pos1 = str.IndexOf(firstString) + firstString.Length; int pos2 = str.Substring(pos1).IndexOf(lastString); return str.Substring(pos1, pos2); } 
+3
Jul 01 '19 at 9:09
source share

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; } 

Using:

 var token = "super exemple of string key : text I want to keep - end of my string"; var keyValue = token.GetStringBetween("key : ", " - "); 
+2
Aug 05 '16 at 17:07
source share

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

 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()); } } 
+2
Oct 24 '18 at 18:05
source share

You already have good answers, and I understand that the code I provide is far from the most efficient and clean. However, I thought it might be useful for educational purposes. We can use ready-made classes and libraries throughout the day. But, not understanding the inner workings, we simply imitate and repeat and never know anything. This code works and is simpler or "virgin" than some 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; } 

As a result, you will get the desired string assigned to the parsedString variable. Keep in mind that it will also capture leading and previous spaces. Remember that a string is just an array of characters that can be manipulated, like other arrays with indexes, etc.

Take care.

+1
Jun 22 '13 at 16:41
source share

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); } 

Note that the System.Text.RegularExpressions link should add

Hope i helped.

0
Feb 25 '15 at 15:25
source share

With dotnetcore 3.0 you can

 var s = "header-THE_TARGET_STRING.7z"; var from = s.IndexOf("-") + "-".Length; var to = s.IndexOf(".7z"); var versionString = f[from..to]; // THE_TARGET_STRING 
0
Sep 19 '19 at 18:22
source share



All Articles