【问题标题】:Regex Get a substring from a string nearest to the end正则表达式从最接近结尾的字符串中获取子字符串
【发布时间】: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


【解决方案1】:
  • PowerShell 的 -match 运算符只能找到(最多)一个匹配项(尽管捕获组可能会找到一个匹配项的多个 子字符串)。
  • 但是,使用量词 *greedy(默认情况下)这一事实,我们仍然可以使用该匹配项在输入中找到 last 匹配项:
    -match '^.*\.(\d{4})\b' 查找输入的 最长 前缀,该前缀以 4 位数字序列结尾,前面是文字 .,后面是单词边界,因此 $matches[1] 包含最后一次出现这种 4 位序列。
Function Extract-Year
{
  param
  (
    [string] $OriginalFileName # Provide the BaseName of the image file.
  )

  if ($OriginalFileName -match '^.*\.(\d{4})\b') {
    $matches[1] # output last 4-digit sequence found
  } else {
    '' # output empty string to indicate that no 4-digit sequence was found.
  }
}

'x.2000.y.2016.z', 'x.y.2016', 'x.y.2016.z', 'x.y.20164.z', 'x.y.201.z' | 
  % { Extract-Year $_ }

产量

2016
2016
2016
# empty line
# empty line

【讨论】:

    猜你喜欢
    • 2017-06-07
    • 2011-07-14
    • 1970-01-01
    • 2018-06-18
    • 2013-10-27
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多