-1

So I'm writing a script in powershell (not the point) where I'd like to match a specific string format, but the string can be longer then my format and I dont want that to be a match. I want it to be a certain length only.

For example. I want my format to match [A-Z]{3}[TLZ]\d{5} but only that. So for example, STSZ43332 is a match, but I dont want to match STSZ433321. I know I could run a if statement before to check the length but was wondering if its possible inside the regex.

If it matters, this is my If statement in powershell.

If ($Name -match "[A-Z]{3}[TLZ]\d{5}") {Write-Host "Found match"}

The problem is that if $name is longer then my expected 9 characters (from the regex} it could still come back as true if the regex string can be found inside $name. As I said, I could do if $name.length to match that $name is only 9 but wanted to know if regex has a way of doing that too.

thanks

Huascar
  • 55
  • 1
  • 5
  • 1
    Dupe of [How do I match an entire string with a regex?](https://stackoverflow.com/questions/4123455/how-do-i-match-an-entire-string-with-a-regex) – Wiktor Stribiżew Jan 21 '21 at 22:39

1 Answers1

0

In regular expressions you can use anchors, which don't match any particular character but make sure your match borders on a given location. In this case, you can use the beginning of line anchor ^ and the end of line anchor $, and then there will be no room for other characters. So your final expression should look like:

^[A-Z]{3}[TLZ]\d{5}$

This won't match unless the beginning of the match is at the start of the string and the end of the match is at the end of the string. If there are any extra characters in there, this won't be the case, so the match will fail.

Charlie Armstrong
  • 2,332
  • 3
  • 13
  • 25