How to check if string Starts with an S, is alpha numeric and has a length of 8?

I’m sure there is a cleaner way to do this. I’m looking for a way to check the following when importing a csv:

  1. String Starts with S
  2. String is alpha numeric
  3. Sting has a length of 8

So far I have this:

$Sites = [System.Collections.Generic.HashSet[string]]::new()
Import-Csv "O:\import.csv" | `
    ForEach-Object {
        If($_.Site -match '^[a-zA-Z0-9]+$' -And $_.Site -like "S*" ) {
            [void]$Sites.Add($_.Site)
        }
    }

Having trouble adding the length part and I’m sure there is a cleaner way to combine all?

Thank you in advance!

The following uses multiple operations, which allows for short-circuiting and therefore only applies regex-matching when necessary:

$_.Site[0] -ceq 'S' -and $_.Site.Length -eq 8 -and $_.Site -notmatch '[^a-z0-9]'

If you wanted to do it with a single regex:

$_.Site -cmatch '^S[a-zA-Z0-9]{7}$'

Note:

  • Both solutions assume that only an uppercase S should be matched:

    • In the multiple-operation solution:

      • -ceq is used, because it is the case-sensitive variant of the -eq, the equality-comparison operator.

      • To match s (lowercase) too, use -eq instead of -ceq

    • In the regex-only solution:

      • -cmatch, the case-sensitive variant of the -match operator is used

      • To match s (lowercase) too, you can simplify to:

        $_.Site -match '^s[a-z0-9]{7}$'
        
  • For the sake of performance, using the separate-operations solution is probably not worth it (especially if you expect most of the inputs to match), but it is arguably more readable than the regex-only solution (at least to those less familiar with regexes).

  • The above solutions only match English (ASCII-range) letters.

Leave a Comment