【发布时间】:2017-03-25 05:49:08
【问题描述】:
我正在尝试使用 powershell 脚本和正则表达式从字符串中获取子字符串。
例如,我试图将年份作为文件名的一部分。
示例文件名“Expo.2000.Brazilian.Pavillon.after.Something.2016.SomeTextIDontNeed.jpg” 问题是正则表达式的结果给了我“2000”而没有其他匹配项。我需要匹配“2016”。可悲的是 $matches 只有一个匹配的实例。我错过了什么吗?我觉得快疯了;)
如果 $matches 将包含找到的所有实例,我可以使用以下方法获取最近的结束实例:
$Year = $matches[$matches.Count-1]
Powershell 代码:
# Function to get the images year and clean up image information after it.
Function Remove-String-Behind-Year
{
param
(
[string]$OriginalFileName # Provide the BaseName of the image file.
)
[Regex]$RegExYear = [Regex]"(?<=\.)\d{4}(?=\.|$)" Regex to match a four digit string, prepended by a dot and followed by a dot or the end of the string.
$OriginalFileName -match $RegExYear # Matches the Original Filename with the Regex
Write-Host "Count: " $matches.Count # Why I only get 1 result?
Write-Host "BLA: " $matches[0] # First and only match is "2000"
}
想要的结果表:
"x.2000.y.2016.z" => "2016" (Does not work)
"x.y.2016" => "2016" (Works)
"x.y.2016.z" => "2016" (Works)
"x.y.20164.z" => "" (Works)
"x.y.201.z" => "" (Works)
【问题讨论】:
-
这个正则表达式对你不起作用有什么原因:
.*\.(\d{4})\.|$?
标签: regex powershell