Home > Software design >  How to find a specific number of digits in string
How to find a specific number of digits in string

Time:12-03

I don't understand the Regex :( I want to find if a path contains only 7 digits For an example:

C:\Users\3D Objects\1403036 --> the result should be 1403036

C:\Users\358712\1403036 --> the result should be 1403036

and so on

I have tried:

$FilesPath -match '([\d{1,7}]{7})')

and

$FilesPath -match '(\d{7})')

Currently I am working with that:

$FilesPath = Read-Host -Prompt
if ($Matches[1].Length -eq '7') {
        $FolderNumber = $Matches[1] 
    }

This is not right because there is no match if the path contains the number 3 in the path

If this is the case:

C:\Users\3D Objects\1403036854 --> More than 7 digits the result should be empty

or

C:\Users\3874113353D Objects\1403036 --> Should return result for 1403036

I don't have an array, just want to get if there is a number with exactly 7 digits and don't if contains less or more than 7 digits

CodePudding user response:

You mean something like this?

# as example the paths as aray to loop over
'C:\Users\3D Objects\1403036', 'C:\Users\358712\1403036', 
'C:\Users\somewhere\1234567', 'C:\Users\3D Objects\1403036854' | ForEach-Object {
    # return the number anchored at the end of the string with exactly 7 digits
    ([regex]'\D(\d{7})$').Match($_).Groups[1].Value
}

Output:

1403036
1403036
1234567

This:

$path = 'C:\Users\3D Objects\1403036'
$result = ([regex]'\D(\d{7})(?:\D|$)').Match($path).Groups[1].Value

directly assigns the match to variable $result and will be the matching numeric value if it matches or $null. Regex method .Match() does not populate the $matches array.

Using the regex operator, which does populate the $matches array, you can also do this:

if ($path -match '\D(\d{7})(?:\D|$)') {
    $result = $matches[1]
}

Regex details:

\D           # Match a single character that is NOT a “digit” (any decimal number in any Unicode script)
(            # Match the regex below and capture its match into backreference number 1
   \d        # Match a single character that is a “digit” (any decimal number in any Unicode script)
      {7}    # Exactly 7 times
)
(?:          # Match the regular expression below
             # Match this alternative (attempting the next alternative only if this one fails)
      \D     # Match a single character that is NOT a “digit” (any decimal number in any Unicode script)
   |
             # Or match this alternative (the entire group fails if this one fails to match)
      $      # Assert position at the end of the string, or before the line break at the end of the string, if any (line feed)
)
  • Related