6.8. Hexadecimal Numbers Within a Certain Range
Problem
You want to match a hexadecimal number within a certain range of numbers. You want the regular expression to specify the range accurately, rather than just limiting the number of digits.
Solution
1 to C (1 to 12: hour or month):
^[1-9a-c]$
Regex options: Case insensitive |
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
1 to 18 (1 to 24: hour):
^(1[0-8]|[1-9a-f])$
Regex options: Case insensitive |
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
1 to 1F (1 to 31: day of the month):
^(1[0-9a-f]|[1-9a-f])$
Regex options: Case insensitive |
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
1 to 35 (1 to 53: week of the year):
^(3[0-5]|[12][0-9a-f]|[1-9a-f])$
Regex options: Case insensitive |
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
0 to 3B (0 to 59: minute or second):
^(3[0-9a-b]|[12]?[0-9a-f])$
Regex options: Case insensitive |
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
0 to 64 (0 to 100: percentage):
^(6[0-4]|[1-5]?[0-9a-f])$
Regex options: Case insensitive |
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
1 to 64 (1 to 100):
^(6[0-4]|[1-5][0-9a-f]|[1-9a-f])$
Regex options: Case insensitive |
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
20 to 7E (32 to 126: printable ASCII codes):
^(7[0-9a-e]|[2-6][0-9a-f])$
Regex options: Case insensitive |
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
0 to 7F (0 to 127: 7-bit number):
^[1-7]?[0-9a-f]$ ...
Get Regular Expressions Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.