views:

276

answers:

6

I have a large piece of text in which there is something simular to this:

!#_KT_#!COMMANDHERE!#_KT_#!

I want, in VB.Net, to get the 'COMMANDHERE' part of the string, how would I go about doing this? I have this so far:

Dim temp As String = WebBrowser1.Document.Body.ToString
Dim startIndex As Integer = temp.IndexOf("!#__KT__#!") + 1
Dim endIndex As Integer = temp.IndexOf("!#__KT__#!", startIndex)
Dim extraction As String = temp.Substring(startIndex, endIndex - startIndex).Trim

TextBox1.Text = extraction

However this only removes the LAST string eg: #_KT_#! COMMAND.

Any help is appreciated!

+2  A: 

IndexOf returns the position of the first character of the pattern in the host string. You add 1 to your startIndex, which is why the first "!" is not included. Change "+ 1" to "+ 10" (the length of your pattern) and it should work as expected.

Jakob Kruse
Thank you! That one character made the difference, thanks alot.
Ben
A: 

startIndex is pointing to the start of your first delimiters string, you need to add its length.

Instead of adding one, try adding "!#__KT__#!".Length;

Francisco Soto
Or better yet, save that string in a constant so you can change it very easily later.
Francisco Soto
A: 

Well, just add the length of the "#KT#!" prefix to the startIndex when extracting substring:

Dim temp As String = WebBrowser1.Document.Body.ToString
Dim startIndex As Integer = temp.IndexOf("!#__KT__#!") + 1
Dim endIndex As Integer = temp.IndexOf("!#__KT__#!", startIndex)
Dim extraction As String = temp.Substring(startIndex + 9, endIndex - startIndex - 9).Trim

TextBox1.Text = extraction 
Fyodor Soikin
A: 

Extract Substring from the Middle of a String here is the link

http://www.example-code.com/vb/mid.asp

anto8421
A: 

Regular expressions can do the trick and looks readable (to me at least ;-):

string command = null;
Regex regex = new Regex (@"!#__KT__#!(?<command>.+)!#__KT__#!");
Match match = regex.Match(commandText);
if (match.Success)
{
    command = match.Groups["command"].Value;
}
bartvdvliet
A: 

I've done something similar to this when breaking out email addresses separated by a semicolon. I've adapted my code to fit your requirement here:

Dim temp As String = WebBrowser1.Document.Body.ToString
Dim stringArray() As String = Split(temp, "!")
TextBox1.Text = stringArray(2)

In this code, your text !#KT#!COMMANDHERE!#KT#! is broken up into the following array:

stringArray(0) 'is equal to nothing
stringArray(1) 'is equal to #_KT_#
stringArray(2) 'is equal to COMMANDHERE
stringArray(3) 'is equal to #_KT_#

I hope that helps!

Tychumsempir