关于正则表达式:从Powershell中的文本文件替换http链接中的内容

Replace content in http link from a text file in powershell

我是powershell的新手,我创建了以下脚本,该脚本提取http://和下一个/之间的内容,进行转换,然后替换初始匹配项:

1
2
3
4
5
6
7
8
9
10
11
$fileName ="myfile"
$newEnvironment ="NewEnvironment"
$config = Get-Content $fileName
$newConfig = $config | % { $_ -replace"http://www.site.de","http://site.de.$newEnvironment" }
$newConfig = $newConfig | % { $_ -replace"http://www.site.com.tr","http://site.com.tr.$newEnvironment" }
$newConfig = $newConfig | % { $_ -replace"http://www.site.fr","http://site.fr.$newEnvironment" }
$newConfig = $newConfig | % { $_ -replace"http://www.site.pl","http://site.pl.$newEnvironment" }
$newConfig = $newConfig | % { $_ -replace"http://www.site-1.be","http://site-1.be.$newEnvironment" }
$newConfig = $newConfig | % { $_ -replace"http://www.site-1.nl","http://site-1.nl.$newEnvironment" }
$newConfig = $newConfig | % { $_ -replace"http://www.site.it","http://site.it.$newEnvironment" }
$newConfig | Set-Content $fileName

我正在尝试使其变得更好,也许使用正则表达式或其他方式,但不使用硬编码文本。
有人可以帮我吗?

我在想类似的东西:

1
2
3
$path ="myFile";
Get-Content $path | Foreach {$_ -replace"(?<=http://).+?(?=/.*)",".+?(?=/.*).newEnvironment"};
Set-Content $path;

但是,即使它是以这种方式设置链接的,它也不起作用:

1
http://.+?(?=/.*).newEnvironment/asd/test.aspx

似乎您想

  • 删除"www."部分
  • $newEnvironment的值附加到任何URL

一种执行此操作的方法是搜索以下内容...

  • 前面带有" http://" — (?<=http://)
  • 以" www。"开头。 — www\\.
  • 组1中的字符不是空格或斜杠-([^/ ]+)
  • 为了安全起见,$ newEnvironment后面没有此符号— (?!\\.$newEnvironment)

,然后将其替换为" regex group 1"""。 $ newEnvironment:

1
2
3
4
5
6
7
$fileName ="myfile"
$newEnvironment ="NewEnvironment"

$pattern ="(?<=http://)www\\.([^/ ]+)(?!\\.$newEnvironment)"
$replacement ="`$1.$newEnvironment"

(Get-Content $path) -replace $pattern,$replacement | Set-Content $path

Powershell运算符通常对数组感到满意。 Get-Content将为您提供一系列行,而-replace将在所有行上工作。 (-replace的另一个实用属性是您可以将其链接:"abc" -replace"a","A" -replace"b","B"将起作用。)

这意味着无需编写手动的foreach循环。唯一需要的是一对括号,因此Get-Content不会将-replace误认为参数。

$1是对第1组的向后引用,反引号是PowerShell的转义字符,因为$本身在Powershell和regex中均具有含义。