Visual Basic .NET Find Hexadecimal Numbers
From Regex Regular Expression Encyclopedia
This recipe will limit the input to numbers and letters that are valid for hexadecimal representations.
[edit] code
Imports System Imports System.IO Imports System.Text.RegularExpressions Public Class Recipe Private Shared _Regex As Regex = New Regex("^[0-9a-f]+$", _ RegexOptions.IgnoreCase) Public Sub Run(ByVal fileName As String) Dim line As String Dim lineNbr As Integer = 0 Dim sr As StreamReader = File.OpenText(fileName) line = sr.ReadLine While Not line Is Nothing lineNbr = lineNbr + 1 If _Regex.IsMatch(line) Then Console.WriteLine("Found match '{0}' at line {1}", _ line, _ lineNbr) End If line = sr.ReadLine End While sr.Close() End Sub Public Shared Sub Main(ByVal args As String()) Dim r As Recipe = New Recipe r.Run(args(0)) End Sub End Class
[edit] How It Works
This recipe uses a simple character class to limit the input to digits and the letters a through f:
| Regular Expression | Description |
|---|---|
| ^ | the beginning of the line, followed by . . . |
| [0-9a-f] | a character class that matches the digits zero through nine and the letters |
| \s | a through f . . . |
| + | found one or more times . . . |
| $ | the end of the line. |
Alternatively, you can replace 0-9 in the character class with \d.
