Regex.Split
, digitsIn VB.NET, it is possible to use Regex.Split
to parse the numbers inside a string
. We use some metacharacters to split on non-digit characters.
When all non-digit characters are treated as delimiters, we can then loop over the parts and use Integer.Parse
to get the integral values from the sequences of digits.
Consider the input string in this example. It contains 3 sequences of digits, and these parts are separated by non-digit parts (unless they occur at the end of string
).
Regex.Split
on non-digit (D) characters. The plus means 1 or more chars in a sequence.String
array) returned by Regex.Split
.Integer.Parse
and add 1 to it to demonstrate we now have an Integer.Imports System.Text.RegularExpressions Module Module1 Sub Main() ' Step 1: declare the input string containing numbers we want to extract. Dim input As String = "ABC 4: 3XYZ 10" Console.WriteLine($"String: {input}") ' Step 2: use Regex.Split on non-digit character sequences. Dim numbers = Regex.Split(input, "\D+") ' Step 3: loop over all results. For Each value As String in numbers ' Step 4: parse the number if it is not Null (Nothing). If Not String.IsNullOrEmpty(value) Dim numeric = Integer.Parse(value) Console.WriteLine("Number: {0} (+1 = {1})", numeric, numeric + 1) End If Next End Sub End ModuleString: ABC 4: 3XYZ 10 Number: 4 (+1 = 5) Number: 3 (+1 = 4) Number: 10 (+1 = 11)
Instead of a complex parsing routine that iterates over characters, we can use Regex.Split
to extract numbers in a string
. It is possible to parse the digits into Integers.