powershell 如何查找字符串中的特定位数

vwkv1x7d  于 2022-12-18  发布在  Shell
关注(0)|答案(1)|浏览(187)

我不明白的正则表达式:(我想找出如果路径只包含7位数例如:

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

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

等等
我试过:

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

以及

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


目前,我正在处理:

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

这是不正确的,因为如果路径中包含数字3,则不存在匹配
如果是这种情况:

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

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

我没有数组,只想获取是否有正好7位数的数字,如果包含少于或多于7位数,则不需要

cetgtptt

cetgtptt1#

你是说像这样的东西?

# 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
}

输出:

1403036
1403036
1234567

这一点:

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


直接将匹配项赋给变量$result,如果匹配或$null,则将是匹配的数值。Regex方法.Match()不填充$matches数组。
使用regex运算符(它填充$matches数组),您还可以执行以下操作:

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

正则表达式详细信息:

\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)
)

相关问题