Home
VB.NET
Regex.Split Digits Example
This page was last reviewed on Jun 10, 2024.
Dot Net Perls
Regex.Split, digits. In 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.
Regex.Split
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.
Example. 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).
Step 1 We print out the input string in the program. As noted, it has 3 digit sequences of 1 or 2 characters each.
Step 2 We use Regex.Split on non-digit (D) characters. The plus means 1 or more chars in a sequence.
Step 3 We loop over the results in the collection (a String array) returned by Regex.Split.
Array
Step 4 If the entry in the array is not Null, we parse it with 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 Module
String: ABC 4: 3XYZ 10 Number: 4 (+1 = 5) Number: 3 (+1 = 4) Number: 10 (+1 = 11)
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 10, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.