C Sharp 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
using System; using System.IO; using System.Text.RegularExpressions; public class Recipe { private static Regex _Regex = new Regex( @"^[0-9a-f]+$", RegexOptions.IgnoreCase ); public void Run(string fileName) { String line; int lineNbr = 0; using (StreamReader sr = new StreamReader(fileName)) { while(null != (line = sr.ReadLine())) { lineNbr++; if (_Regex.IsMatch(line)) { Console.WriteLine("Found match '{0}' at line {1}", line, lineNbr); } } } } public static void Main( string[] args ) { Recipe r = new Recipe(); r.Run(args[0]); } }
[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.
