获取string中两个string之间的string

我有一个string:

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

我只想保留"key : "" - "之间的string。 我怎样才能做到这一点? 我必须使用正则expression式还是可以用另一种方式来完成?

也许,一个好方法就是删除一个子string:

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

或者只是string操作

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

你可以做到没有正则expression式

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

正则expression式在这里是过度的。

可以使用string.Split与分隔符需要一个string[]的重载,但这也是矫枉过正。

查看SubstringIndexOf – 前者获取给定的string的部分和索引和长度,第二个查找索引的内部string/字符。

取决于你希望实现的强大/灵活性,这实际上可能有点棘手。 这是我使用的实现:

 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 " 

或者,用正则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; 

与一个运行的例子 。

你可以决定是否过度杀伤。

要么

作为未经validation的扩展方法

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

这是我能做到的方式

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

一个可用的LINQ解决scheme:

 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 

由于:-是独一无二的,你可以使用:

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

您可以使用下面的扩展方法:

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

用法是:

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

我认为这工作:

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

你已经有了一些很好的答案,我意识到我所提供的代码远没有那么高效和干净。 不过,我认为这对于教育目的可能是有用的。 我们可以整天使用预build的类和库。 但是,如果不理解内在的作用,我们只是模仿和重复,而不会学到任何东西。 这个代码起作用,比其他一些更基本或“处女”:

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

您最终将分配给parsedStringvariables的所需string。 请记住,它也将捕获进程和前面的空间。 请记住,一个string只是一个字符数组,可以像其他具有索引的数组一样操作。

保重。

正如我总是说什么都不是不可能的:

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

记住应该添加System.Text.RegularExpressions的引用

希望我帮助。