【问题标题】:How to find a specific number of digits in string如何在字符串中查找特定数量的数字
【发布时间】:2022-12-02 21:25:30
【问题描述】:

我不明白正则表达式:( 我想查找路径是否仅包含 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 位数字则没有

【问题讨论】:

    标签: powershell


    【解决方案1】:

    你的意思是这样的?

    # as example the paths as aray to loop over
    'C:UsersD Objects`3036', 'C:Users8712`3036', 
    'C:UserssomewhereS4567', 'C:UsersD Objects`3036854' | 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:UsersD Objects`3036'
    $result = ([regex]'D(d{7})(?:D|$)').Match($path).Groups[1].Value
    

    直接将匹配分配给变量$result,如果匹配或$null将是匹配的数值。正则表达式方法.Match() 不填充 $matches 数组。

    使用正则表达式操作员,它确实填充了 $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)
    )
    

    【讨论】:

    • 请查看更新后的消息
    • @Bandit 该数组只是作为示例显示(如果您愿意,可以进行演示)。当然你可以像$result = ([regex]'D(d{7})$').Match('C:UsersD Objects`3036').Groups[1].Value这样逐个字符串地做,这将返回数字1403036$null例如$result = ([regex]'D(d{7})$').Match('C:UsersD Objects`3036854').Groups[1].Value
    • 你是说像这样? if (([regex]'D(d{7})$').Match($FilesPath).Groups[1].Value) { $FolderNumber = $Matches[1] }
    • 这不适用于 C:Temp`3036_140303
    • @Bandit,不,您将正则表达式方法 .Match() 与您可以使用操作员-match..我会尽快更新我的答案
    猜你喜欢
    • 2023-01-23
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 2022-01-17
    相关资源
    最近更新 更多