You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell技术求助:如何高效截取URL指定部分并存入变量

嘿,你已经写出了可行的代码,真棒!这里有几个更简洁高效的PowerShell方案,能帮你更优雅地完成从URL中提取目标字符串的任务:

先回顾下你已实现的可行代码

$rightPart="https://thoudamchitaranjan.blogspot.in/2017/12/merry-christmas-and-still-merry-shes-still-so-beautiful.html"
$rightPart=$rightPart.Replace(".html","")
while($rightPart -imatch "/"){
    $pos = $rightPart.IndexOf("/")
    $rightPart = $rightPart.Substring($pos+1)
}
Write-Output "String is: $rightPart"

优化方案1:利用.NET Uri类和文件路径工具

这个方案借助.NET的Uri类解析URL结构,再用Path工具直接去掉文件后缀,代码简洁且可读性强:

$url = "https://thoudamchitaranjan.blogspot.in/2017/12/merry-christmas-and-still-merry-shes-still-so-beautiful.html"
# 解析URL为Uri对象
$uri = [Uri]$url
# 取路径最后一段,再去掉.html后缀
$rightPart = [System.IO.Path]::GetFileNameWithoutExtension($uri.Segments[-1])
Write-Output "String is: $rightPart"

说明:$uri.Segments会返回URL中所有路径段的数组,[-1]直接获取最后一段(即带.html的部分);GetFileNameWithoutExtension方法专门用于去除文件后缀,一步到位。

优化方案2:使用字符串分割与过滤

通过分割字符串并过滤无效元素,快速定位目标内容:

$url = "https://thoudamchitaranjan.blogspot.in/2017/12/merry-christmas-and-still-merry-shes-still-so-beautiful.html"
# 按斜杠分割URL,过滤空字符串后取最后一个元素,再去掉.html
$rightPart = ($url -split '/' | Where-Object { $_ }) [-1] -replace '\.html$', ''
Write-Output "String is: $rightPart"

说明:-split '/'将URL拆分为数组,Where-Object { $_ }剔除分割后产生的空字符串(比如开头//分割出的空元素);-replace '\.html$', ''精准移除结尾的.html后缀。

优化方案3:正则表达式精准匹配

用正则直接匹配最后一段目标内容,适合固定格式的URL场景:

$url = "https://thoudamchitaranjan.blogspot.in/2017/12/merry-christmas-and-still-merry-shes-still-so-beautiful.html"
# 匹配最后一个斜杠后、.html前的所有非斜杠字符
if ($url -match '\/([^\/]+)\.html$') {
    $rightPart = $matches[1]
    Write-Output "String is: $rightPart"
}

说明:正则\/([^\/]+)\.html$的意思是:匹配最后一个/,然后捕获所有不是/的字符(也就是我们要的目标内容),直到结尾的.html;捕获到的内容会存在$matches[1]中。

这些方案都避免了循环操作,代码更简洁,执行效率也更高,你可以根据自己的习惯选择使用~

内容的提问来源于stack exchange,提问作者thoudamchitaranjan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:46:57