qckmini6
qckmini6

Reputation: 124

Split text to get certain value

How can I split this xml node to get only the number value?

<span>All Potatoes: 4</span>

Something like this:

Dim code as string = "<span>All Potatoes: 4</span>"
Dim splitrsult as string
Splitresult = splitresult("<span>All Potatoes:" & "</span>")
Msgbox(splitresult)

I'm newbie in this language, and help would be appreciate it. Thank you!

Upvotes: 4

Views: 116

Answers (3)

T.S.
T.S.

Reputation: 19348

As another answer mentions, use XML parser to get the value between tags. Once that is done, if your text definitely has format of description : <value>, the most efficient way would be to split string

Dim description As String = node.Value
Dim value As Integer = Integer.Parse(description.Split(": ")(1).Trim())

But if you don't guarantee that there will be something after :, you can use Integer.TryParse. And if there is no guarantee that there is only one :, you can take last element of array

Dim a() Ad String = description.Split(":")
Dim val As Integer 
If Not Integer.TryParse(a(a.Length - 1), val) Then
    MessageBox.Show("Value is not found")
Else
    MessageBox.Show("Value is " & val.ToString())
End If

Regex is expensive and only needed when you look for patterns within text. If you have structured text, you don't have to use regex

Upvotes: 2

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112447

Handle the XML as XML! (not as a simple string)

Use this imports statement

Imports System.Xml.Linq

Then parse your string in order to get an Xml element and get its value

Dim code As String = "<span>All Potatoes: 4</span>"
Dim node = XElement.Parse(code)
Dim result As String = node.Value ' ==> "All Potatoes: 4"

Upvotes: 3

Fᴀʀʜᴀɴ Aɴᴀᴍ
Fᴀʀʜᴀɴ Aɴᴀᴍ

Reputation: 6251

To get the number value using Regex: (It's simple. Never be afraid of Regex)

Dim code as string = "<span>All Potatoes: 4</span>"
resultString = Regex.Match(code, @"\d+").Value

Upvotes: 2

Related Questions