0

I am attempting to validate a string to ensure it's a valid registry path, and having trouble with the non printing characters part. Given these three strings

$stringLiteral = 'line`nline'
$stringEscape = "line`nline"
$string = "lineline"

I should also find a non printing character in $stringEscape. Using a simple regex pattern that only searches for the one escaped character here works. So

$pattern = "`n"
$stringLiteral -match $pattern
$stringEscape -match $pattern
$string -match $pattern

correctly returns

False
True
False

However, I want to search on all the non printing characters defined here. So I was thinking a character set like this would work.

$pattern = '[`0`a`b`e`f`n`r`t`v]'

But that returns true for all three tests. I have also tried

$pattern = '[`0|`a|`b|`e|`f|`n|`r|`t|`v]'
$pattern = '`0`a`b`e`f`n`r`t`v'
$pattern = '`0|`a|`b|`e|`f|`n|`r|`t|`v'

None of which work, but as expected with different failure modes. What is the trick here?

Gordon
  • 6,257
  • 6
  • 36
  • 89
  • 1
    You used single quotes in ``$pattern = '[`0`a`b`e`f`n`r`t`v]'``. Use double quotes. Maybe you need to match all control chars? Use `$pattern = '\p{Cc}'` then. – Wiktor Stribiżew Jun 16 '21 at 07:57
  • Ugh, I coped the wrong bit. I had remarked all the single quotes, and tested with double quotes, but I copied the single quotes here. Need more coffee I think. Thing is, for me double quotes doesn't change anything. the two `[...]` patterns return True for all three tests, and the two `...` patterns return False for all three tests. ``$pattern = "[`0`a`b`e`f`n`r`t`v]"`` is what I really expected would work. – Gordon Jun 16 '21 at 08:04
  • And I wonder how you got your formatting to work in the comment, since just wrapping the code with back ticks didn't work for me, I needed to use the code button in the original post, which isn't an option in a comment. EDIT: Aha, double backpacks on the wrapping backpacks, not on the internal ones. Woot. – Gordon Jun 16 '21 at 08:06
  • 1
    Use double backtick to format code with backticks in the comments. – Wiktor Stribiżew Jun 16 '21 at 08:07
  • Hmm, ``$pattern = '\p{Cc}'`` seems to be working. I just wonder what else is going to be caught that is actually a valid character in a registry path? It's an edge case to be sure, but I would like to get it right. Sadly `Test-Path -isValid` doesn't work at all. – Gordon Jun 16 '21 at 08:09
  • `\p{Cc}` matches `[\u0000-\u001F\u007F-\u009F]` – Wiktor Stribiżew Jun 16 '21 at 08:11
  • I'll need to go look those up at some point, but I think I can at least proceed with this for now, and verify if I am being too greedy later. Thanks! – Gordon Jun 16 '21 at 08:15

0 Answers0