I have some string
bla bla bla bla <I NEED THIS TEXT>
What is the best and fastest way to get text inside <>
?
I have some string
bla bla bla bla <I NEED THIS TEXT>
What is the best and fastest way to get text inside <>
?
int start = s.IndexOf("<") + 1;
int end = s.IndexOf(">",start);
string text = s.Substring(start,end - start);
var s = "bla bla bla bla <I NEED THIS TEXT> ";
Console.WriteLine(s.Substring(s.IndexOf('<') + 1, s.IndexOf('>') - s.IndexOf('<') - 1));
var input = "bla bla bla bla <I NEED THIS TEXT> ";
var match = Regex.Match(input, @".*?<(?<MyGroup>.*?)>");
if (match.Success)
var text = match.Groups["MyGroup"].Value;
Will there be nesting? Two of the answers above will give different results:
static void Main()
{
string s = "hello<I NEED <I NEED THIS TEXT> THIS TEXT>goodbye";
string r = Regex.Match(s, "<(.*)>").Groups[1].Value;
int start = s.IndexOf("<") + 1;
int end = s.IndexOf(">", start);
string t = s.Substring(start, end - start);
Console.WriteLine(r);
Console.WriteLine(t);
Console.ReadKey();
}
Without regex, and checking of sorts:
var data = "bla bla bla bla <I NEED THIS TEXT>";
int start = 0, end = 0;
if ((start = data .IndexOf("<")) > 0 &&
(end = data .IndexOf(">", start)) > 0)
{
var result = data .Substring(start + 1, end - start - 1);
}
Using string.SubString and IndexOf mwthods will only work is "<" and ">" are the start and end of the text you want. If these characters happen to be included before the actual text starts then you wont get correct string.
The best thing is to use regular expressions.
var input = "bla bla bla bla <I NEED THIS TEXT>";
Match match = Regex.Match(input, @"<([^>]*)>");
if (match.Success)
{
// Do some with match.Groups[1].Value;
}