Powershell Regex validate computer name

Viewed 275

I love this site, people are so helpful...

This is a more specific question but is in reference to (https://stackoverflow.com/questions/62580859/using-regex-for-complicated-naming-convention)

Both @Witker and @AdminofThings solved a big problem for a computer name validation checker I'm developing. Thank you both!.

The examples I gave before was something I could use to build on. However I have one little issue that I can't figure out with a portion of the regex to match the special identifier. Let me explain:

I need a regex that can parse these sets of numbers (the pound symbol is just any numbers):

  1######
  2######
  3######
  4######
  37#####
  47#####

To better understand, I need way to look at the first two digits of any set of 6 numbers and see if they match one of these criteria. Here are some examples of matches:

234556 <-- single match [2]
012345 <-- no match [0]
346980 <-- single match [3]
379456 <-- double match [37]
435794 <-- single match [4]
471234 <-- double match [47]
171234 <-- single match [1] not double match [17]

The problem I see is when there is a 1 followed by a 7 its matches as two digits; but I need it to see it the 1 being a single identifier.

if I use a different regex, I am seeing a 37 being a single match when I need it to be matched as a double 37.

I was hoping I can do this all in one regex without having to do if else statements. Regex's I have tried are:

(?<identifier>[1234](7)?)
(?<identifier>[1234]([34]7)?)
(?<identifier>[1234]([34|47])
(?<identifier>[1234]\d{1}|[37|47]\d{2})
(?<identifier>[1234]|37|47)
(?<identifier>1|2|3|4|37|47)

Please help...again. ;)

1 Answers

If I understand your requirements correctly, you may use the following pattern:

\b(?=.{6}\b)(?<identifier>37|47|[1234])\d+

Demo.

Breakdown:

\b              # Word boundary assertion.
(?=.{6}\b)      # A Lookahead to make sure the number is exactly 6 digits.
(?<identifier>  # Start of the 'identifier' capturing group.
    37|47       # Search for '37' or '47' first.
    |[1234]     # If not found, search for any digit in this character class.
)               # End of the capturing group
\d+             # Match any number of digits (max. 6 in total because of the Lookahead).

If you only care about the identifier and don't want to include the remaining digits in the match (but still want to make sure they're there), you may change the pattern above to:

\b(?=\d{6}\b)(?<identifier>37|47|[1234])

Demo.

..or make it simpler without a capturing group:

\b(?=\d{6}\b)(?:37|47|[1234])
Related