在powershell中给出不带前两个或三个字母的字符串

在powershell中给出不带前两个或三个字母的字符串,powershell,powershell-2.0,Powershell,Powershell 2.0,我想从一行中读出一个字符串。电话是 ERROR: file'C:\Program Files (x86)\movies\action\Theincrediblehulk.mp3' is missing 我只要 Theincrediblehulk.mp3 我用来获取该字符串的代码是 Select-String tt.txt -pattern [regex]"[A-Za-z]+\.mp3" -AllMatches | % { $_.Matches } | % { $_.Value } 但

我想从一行中读出一个字符串。电话是

 ERROR: file'C:\Program Files (x86)\movies\action\Theincrediblehulk.mp3' is missing
我只要

 Theincrediblehulk.mp3 
我用来获取该字符串的代码是

Select-String tt.txt -pattern [regex]"[A-Za-z]+\.mp3" -AllMatches | % { $_.Matches } | % { $_.Value }
但它给我的输出是

crediblehulk.mp3
前两三个字不见了。 请提出更好的解决方法。我之所以使用[A-Za-z],是因为名称是动态的。

首先抓取引号之间的所有内容:

$Filepaths = Select-String tt.txt -pattern "'([^']+)'" -AllMatches | % { $_.Matches } | % { $_.Groups[1].Value }
现在,您可以使用
splitpath-Leaf
获取文件名:

$Filenames = $Filepaths |Split-Path -Leaf
Path.GetFileName()

首先抓取引号之间的所有内容:

$Filepaths = Select-String tt.txt -pattern "'([^']+)'" -AllMatches | % { $_.Matches } | % { $_.Groups[1].Value }
现在,您可以使用
splitpath-Leaf
获取文件名:

$Filenames = $Filepaths |Split-Path -Leaf
Path.GetFileName()


Mathias R.Jessen的答案是一个更好的解决方案,但是这个答案解释了为什么原始代码没有按预期工作


我假设从您的
[regex]
开始,您试图告诉powershell将字符串转换为regex对象。然而,powershell实际上将您的论点解释为

-pattern '[regex]"[A-Za-z]+\.mp3"'
如果确实希望将字符串显式地视为正则表达式对象,则需要将值括在括号中

-pattern ([regex]"[A-Za-z]+\.mp3")
虽然正则表达式转换不是必需的,但仅字符串就足够了

-pattern '[A-Za-z]+\.mp3'

Mathias R.Jessen的答案是一个更好的解决方案,但是这个答案解释了为什么原始代码没有按预期工作


我假设从您的
[regex]
开始,您试图告诉powershell将字符串转换为regex对象。然而,powershell实际上将您的论点解释为

-pattern '[regex]"[A-Za-z]+\.mp3"'
如果确实希望将字符串显式地视为正则表达式对象,则需要将值括在括号中

-pattern ([regex]"[A-Za-z]+\.mp3")
虽然正则表达式转换不是必需的,但仅字符串就足够了

-pattern '[A-Za-z]+\.mp3'