C# 获取字符串中两个字符串之间的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17252615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get string between two strings in a string
提问by flow
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?
我只想保留介于"key : "和之间的字符串" - "。我怎样才能做到这一点?我必须使用正则表达式还是可以用其他方式来做?
回答by I4V
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);
回答by Oded
Regex is overkill here.
正则表达式在这里有点矫枉过正。
You coulduse string.Splitwith the overload that takes a string[]for the delimiters but that would alsobe overkill.
您可以使用string.Split将 astring[]作为分隔符的重载,但这也太过分了。
Look at Substringand 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.
查看Substring和IndexOf- 前者获取给定字符串的一部分、索引和长度,第二个用于查找内部字符串/字符的索引。
回答by Dmitry Bychenko
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);
回答by Anirudha
You can do it without regex
你可以不用正则表达式
input.Split(new string[] {"key :"},StringSplitOptions.None)[1]
.Split('-')[0]
.Trim();
回答by flyNflip
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.
您最终将所需的字符串分配给 parsedString 变量。请记住,它还将捕获进行中和前面的空格。请记住,字符串只是一个字符数组,可以像其他具有索引等的数组一样进行操作。
Take care.
小心。
回答by ChaseMedallion
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 "
回答by Dejan Ciev
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);
回答by Vijay Singh Rana
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;
}
回答by Slavi
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
记住应该添加 System.Text.RegularExpressions 的引用
Hope That I Helped.
希望我有所帮助。
回答by w.b
A working LINQ solution:
一个有效的 LINQ 解决方案:
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

