I know you already have accepted an answer, however, I'd like to suggest another alternative. I'm assuming, based on the context of your question and the example that you provided, that your intention is to parse a list of bytes, where each byte is represented by a two digit hexadecimal value.
If you use regex to find your matches, it will be more powerful. For instance, you can easily ignore all white-space characters (e.g. tabs, new-lines) and you can easily validate the data to make sure that only properly formatted bytes are in the string (i.e. 00
- FF
). For instance, you could do something like this:
Dim bytes As New List(Of String)()
Dim m As Match = Regex.Match(TextBox1.Text, "^\s*((?<byte>[a-fA-F0-9]{2})\s*)*$")
If m.Success Then
Dim g As Group = m.Groups("byte")
If g.Success Then
For Each c As Capture In g.Captures
bytes.Add(c.Value)
Next
End If
Else
MessageBox.Show("Input is not properly formatted")
End If
However, if the idea is to parse the actual byte values, you can do so using Byte.Parse
, like this:
Dim bytes As New List(Of Byte)()
Dim m As Match = Regex.Match(TextBox1.Text, "^\s*((?<byte>[a-fA-F0-9]{2})\s*)*$")
If m.Success Then
Dim g As Group = m.Groups("byte")
If g.Success Then
For Each c As Capture In g.Captures
bytes.Add(Byte.Parse(c.Value, NumberStyles.HexNumber))
Next
End If
Else
MessageBox.Show("Input is not properly formatted")
End If
Both of those examples use the same regex pattern to find all of the hexadecimal bytes in the string. The pattern it uses is:
^\s*((?<byte>[a-fA-F0-9]{2})\s*)*$
Here's the meaning of the regex pattern:
$
- The match must start at the beginning of the string (i.e. no invalid text can come before the bytes)
\s*
- Any number of white-space characters can come before the first byte
\s
- Any white-space character
*
- Zero or more times
((?<byte>[a-fA-F0-9]{2})\s*)*
- Any number of bytes, each separated by any number of white-space characters
(
- Begins the group so that we can later apply a kleene star to the whole group (which means the whole group can repeat any number of times)
(?<byte>
- Begins another, inner group which is named "byte"
. It is given a name so that we can easily reference the values captured by the group in the VB code.
[a-fA-F0-9]{2}
- A two-digit hexadecimal byte (i.e. 00
- FF
)
[a-fA-F0-9]
- Any character between a
and f
or between A
and F
or between 0
and 9
{2}
- There must be exactly two characters matching that specification
)
- Ends the group named "byte"
. Notice that this named-group only captures the two actual hexadecimal digits. It does not capture any of the white-space between the bytes.
\s*
- There can be any number of white-space characters after a byte
)
- The ends outer group which includes a byte and all of the white-space that comes after it
*
- The aforementioned kleene star meaning that the outer-group can repeat any number of times
$
- The match must end at the ending of the string (i.e. no invalid text can come after the bytes)