Hexadecimal-counting I’ve been playing with pattern matching in Powershell.

I was trying to use ‘-match’ to ‘Check if the string is a hexadecimal number’ for the ‘Perl one-liners in Powershell’ page I’ve been working on.

I can’t pretend to entirely understand or explain pattern matching in Powershell, or in linux, but this seems to work.

$X = "21e" ; $Y = $X.length ; $X -match "[0123456789abcde]{$Y}"

This says match the string against ‘any combination of the characters within the square brackets (i.e. the hex digits) to the same length as the original string’.

So, the square brackets contain the allowable characters.

The curly brackets give the number of characters.

I tried just doing:

$X = "21e" ; $X -match "[0123456789abcde]{$X.length}"

…but this didn’t seem to work.

Tests

I tried the following strings - they all seemed to come up with the right answer: ``` $ $X = "21e" ; $Y = $X.length ; $X -match "[0123456789abcde]{$Y}" True $ $X = "21edjhsd" ; $Y = $X.length ; $X -match "[0123456789abcde]{$Y}" False $ $X = "21e34782348237847832748723" ; $Y = $X.length ; $X -match "[0123456789abcde]{$Y}" True $ $X = "21e34782348237847832748723f" ; $Y = $X.length ; $X -match "[0123456789abcde]{$Y}" False $ $X = "21e34782348237847832748723acbdaaa" ; $Y = $X.length ; $X -match "[0123456789abcde]{$Y}" True $ $X = " " ; $Y = $X.length ; $X -match "[0123456789abcde]{$Y}" False ```

….although I’m not sure whether this is right or wrong:

$ $X = "" ; $Y = $X.length ; $X -match "[0123456789abcde]{$Y}"
True