【问题标题】:Replacing sub strings with regex in powershell在powershell中用正则表达式替换子字符串
【发布时间】: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


    【解决方案1】:

    如果我遗漏了什么,请原谅我,但在我看来,你真正想要实现的只是去掉 /en 部分,最后将整个 url 转换为小写。

    鉴于您的示例网址,这可能很简单:

    $url = 'https://www.oursite.org/en/News-and-Articles/2017/11/article-name'
    $replaceValue = ($url -replace '/en/', '/').ToLower()
    

    结果:

    https://www.oursite.org/news-and-articles/2017/11/article-name

    如果涉及更复杂的替换,请编辑您的问题并给我们更多示例和所需的输出。

    【讨论】:

      【解决方案2】:

      试试正则表达式:(?<=oursite\.org\/)(?:en\/)?News-and-Articles(?=\/)

      替换为news-and-articles

      Demo

      【讨论】:

      • 请原谅我的无知,我该如何将它插入我拥有的代码中?抱歉,我继承了这个我对 powershell 几乎没有经验
      猜你喜欢
      • 1970-01-01
      • 2019-04-17
      • 2012-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-19
      相关资源
      最近更新 更多