Whitespace example. One use for the Regex.Split function is to break up an input string based on whitespace. Sometimes, an input string may have more than one whitespace character in a row.
Tip Treating more than one whitespace as a single whitespace is useful. The pattern is \s+ and it indicates one or more whitespace characters.
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
' The input string.
Dim expression As String = "3 * 5 = 15"' Call Regex.Split.
Dim operands() As String = Regex.Split(expression, "\s+")
' Loop over the elements.
For Each operand As String In operands
Console.WriteLine(operand)
Next
End Sub
End Module3
*
5
=
15
Number example. Please notice that the Imports System.Text.RegularExpressions directive is used at the top of this program. This includes the Regex type into the current program.
And We call the Regex.Split function and pass the pattern \D+ to it. This means one or more non-digit characters.
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
' The input string.
Dim sentence As String = "10 cats, 20 dogs, 40 fish and 1 programmer."' Invoke the Regex.Split shared function.
Dim digits() As String = Regex.Split(sentence, "\D+")
' Loop over the elements in the resulting array.
For Each item As String In digits
Console.WriteLine(item)
Next
End Sub
End Module10
20
40
1
Uppercase words. Sometimes Regex.Split can be used with additional code in a VB.NET For Each loop to test each string. This allows us to filter the results in an imperative way.
Step 1 We split on non-word characters by calling Regex.Split with the metacharacter "\W".
Step 2 We use a For Each loop over the resulting string array and test each string for an uppercase first letter.
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim sentence As String = "Bob and Michelle are from Indiana."' Step 1: split on non-word characters.
Dim words = Regex.Split(sentence, "\W")
' Step 2: test all resulting strings and find uppercase words.
For Each word in words
If Not String.IsNullOrEmpty(word) AndAlso Char.IsUpper(word(0))
Console.WriteLine(word)
End If
Next Word
End Sub
End ModuleBob
Michelle
Indiana
Summary. We examined the Regex.Split function. With it, you can split strings based on patterns more complex than is possible with the String type's Split function.
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 18, 2024 (new example).