Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract part of a string between point A and B

Tags:

I am trying to extract something from an email. The general format of the email will always be:

blablablablabllabla hello my friend.  [what I want]  Goodbye my friend blablablabla 

Now I did:

                    string.LastIndexOf("hello my friend");                     string.IndexOf("Goodbye my friend"); 

This will give me a point before it starts, and a point after it starts. What method can I use for this? I found:

String.Substring(Int32, Int32) 

But this only takes the start position.

What can I use?

like image 376
TheGateKeeper Avatar asked Feb 29 '12 19:02

TheGateKeeper


2 Answers

Substring takes the start index (zero-based) and the number of characters you want to copy.

You'll need to do some math, like this:

string email = "Bla bla hello my friend THIS IS THE STUFF I WANTGoodbye my friend"; int startPos = email.LastIndexOf("hello my friend") + "hello my friend".Length + 1; int length = email.IndexOf("Goodbye my friend") - startPos; string sub = email.Substring(startPos, length); 

You probably want to put the string constants in a const string.

like image 98
Eric J. Avatar answered Sep 24 '22 18:09

Eric J.


you can also use Regex

string s =  Regex.Match(yourinput,                         @"hello my friend(.+)Goodbye my friend",                          RegexOptions.Singleline)             .Groups[1].Value; 
like image 41
L.B Avatar answered Sep 21 '22 18:09

L.B