为什么此代码在 PowerShell 中有效,但它在 html 文件中没有任何改变(使用正则表达式)

Why this code works in PowerShell but it doesn't change nothing in the html file (with Regex)

我有 file1.html 行:

<bogus></bogus>
 <title>Something goes here</title>
 <TheEnd>END</TheEnd>

我用正则表达式制作了 3 个不同的 PowerShell 脚本以更改此行: <title>Something goes here</title>:

  $path = 'c:\Folder1\file1.html'
  $Content = Get-Content -Path $path
           
  foreach($Line in $Content){
      $Line -replace "<title>(.*?)</title>",' NEW is now there!'  #This regex selects everything between tags and make a replace:
  }
  Set-Content -Path $Path -Value $Line

$Content = Get-Content -Path c:\Folder1\file1.html  
  
   foreach($Line in $Content){
       $Line -replace "<title>(.*?)</title>",' NEW is now there!'  #This regex selects everything between tags and make a replace:
   }
  Set-Content -Path $Path -Value $Line

$path = 'c:\Folder1\file1.html'
$Content = Get-Content -Path $path  
$GetTitle = [regex]"<title>(.*?)</title>"
 foreach($Line in $Content){
     $Line -replace $GetTitle,' NEW is now there!'  #This regex selects everything between tags and make a replace:
 }
  Set-Content -Path $Path -Value $Line

输出应该是。

<bogus></bogus>

<title>NEW is now there!</title>

<TheEnd>END</TheEnd>

提到我的所有代码都在 PowerShell 中运行,但在 File1.html 中没有进行任何更改。那就是问题所在。谁能纠正我的代码?

使用正则表达式 -replace,您需要考虑要保留的内容并将其捕获到反向引用中。 在您的情况下,您想保留 <title></title>,并替换这些标签之间的内容。

将正则表达式更改为 '(<title>).*?(</title>)'

此外,您可以使用 Get-Content 上的 -Raw 开关将文件作为单个多行字符串读取,进行替换并将结果直接通过管道传递给 Set-Content

$path = 'c:\Folder1\file1.html'
(Get-Content -Path $path -Raw) -replace '(<title>).*?(</title>)', 'NEW is now there!' |
    Set-Content -Path $Path

详情:

'' +                     Insert the text that was last matched by capturing group number 1
' NEW is now there!' +     Insert the character string “ NEW is now there!” literally
''                       Insert the text that was last matched by capturing group number 2
 $path = 'c:\Folder1\file1.html'
 $Content = Get-Content -Path $path 
 $newContent =@() 
 $RegexForTitle = '(?<=title>).*(?=</title>)'
 foreach($Line in $Content)
 {
     $newContent += $Line -replace $RegexForTitle,'NEW IS NOW HERE!'
 } 
 Set-Content -Path $Path -Value $newContent

 #optional this line

'| Out-File -path file1.html'