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 betw
I used the code snippet from Vijay Singh Rana which basically does the job. But it causes problems if the firstString
does already contain the lastString
. What I wanted was extracting a access_token from a JSON Response (no JSON Parser 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);
}
Something like this perhaps
private static string Between(string text, string from, string to)
{
return text[(text.IndexOf(from)+from.Length)..text.IndexOf(to, text.IndexOf(from))];
}
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;
}
In C# 8.0 and above, you can use the range operator ..
as in
var s = "header-THE_TARGET_STRING.7z";
var from = s.IndexOf("-") + "-".Length;
var to = s.IndexOf(".7z");
var versionString = s[from..to]; // THE_TARGET_STRING
See documentation for details.
You can do it without regex
input.Split(new string[] {"key :"},StringSplitOptions.None)[1]
.Split('-')[0]
.Trim();
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);