【发布时间】:2019-03-30 02:49:05
【问题描述】:
我的 powershell 中有以下正则表达式代码来识别我需要更新的 URL:
'href[\s]?=[\s]?\"[^"]*(https:\/\/oursite.org\/[^"]*News and Articles[^"]*)+\"'
'href[\s]?=[\s]?\"[^"]*(https:\/\/oursite.org\/[^"]*en\/News-and-Articles[^"]*)+\"'
这些为我提供了我需要更新的结果,现在我需要知道如何将值“News and Articles”替换为“news-and-articles”和“en”替换为“news-and-articles”。
我有一些代码具有这样的替换 url:
$newUrl = 'href="https://oursite.org/"' #replaced value
所以开始的结果是:
https://www.oursite.org/en/News-and-Articles/2017/11/article-name
替换为
https://www.oursite.org/news-and-articles/2017/11/article-name
这是遍历所有文章并进行替换的函数:
function SearchItemForMatch
{
param(
[Data.Items.Item]$item
)
Write-Host "------------------------------------item: " $item.Name
foreach($field in $item.Fields) {
#Write-Host $field.Name
if($field.Type -eq "Rich Text") {
#Write-Host $field.Name
if($field.Value -match $pattern) {
ReplaceFieldValue -field $field -needle $pattern -replacement $newUrl
}
#if($field.Value -match $registrationPattern) {
# ReplaceFieldValue -field $field -needle $registrationPattern -replacement $newRegistrationUrl
#}
if($field.Value -match $noenpattern){
ReplaceFieldValue -field $field -needle $noenpattern -replacment $newnoenpattern
}
}
}
}
这里是替换方法:
Function ReplaceFieldValue
{
param (
[Data.Fields.Field]$field,
[string]$needle,
[string]$replacement
)
Write-Host $field.ID
$replaceValue = $field.Value -replace $needle, $replacement
$item = $field.Item
$item.Editing.BeginEdit()
$field.Value = $replaceValue
$item.Editing.EndEdit()
Publish-Item -item $item -PublishMode Smart
$info = [PSCustomObject]@{
"ID"=$item.ID
"PageName"=$item.Name
"TemplateName"=$item.TemplateName
"FieldName"=$field.Name
"Replacement"=$replacement
}
[void]$list.Add($info)
}
【问题讨论】:
标签: regex powershell