Powershell Extract Number from File Name

走远了吗. 提交于 2019-12-13 08:26:13

问题


Files names could be:

1234_billing.txt
1234billling.txt
123_billing.txt
123billing.txt

How can I extract the only the number in all 4 cases? I've tried -split and $_.BaseName.Substring() but can't seem to get it correct.


回答1:


Assuming that the filenames are in the array variable $flist, the following will do the trick:

foreach ($file in $flist) {
    if ($file -match "\d+") {
        $matches.value
    }
}

The -match operator takes as its right operand a regex pattern; in this case we use the pattern \d+ to signal any non-zero number of consecutive digits. The operator returns either $true or $false, and stores the matched substring in $matches. There's more about the -match operator at Get-Help about_Operators, and everyone can use a handy reference for regular expressions.



来源:https://stackoverflow.com/questions/48409026/powershell-extract-number-from-file-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!