regex - “the regular expression pattern is not valid”,同时用数组替换正则表达式

标签 regex powershell

在下面的代码中,我试图用保存正确代码的css文件替换无法正常运行的css文件的一部分。

在第1部分中,我获得了两个文件。

在第2部分中,我使用正则表达式从bad.css过滤了无效部分。

在第3部分中,我想用good.css文件替换坏的CSS。但是我收到错误“正则表达式模式无效”。

应该注意的是,$b是Array的类型,$d是String的类型。但是我真的不知道这是否有所作为。

#1. get files
$overrider = (Join-Path $powerShellResourcePath "good.css")
$b = Get-Content $overrider

$stylingOverride = (Join-Path $contentPath "bad.css")
$c = Get-Content $stylingOverride

#2. gets the part that should be replaced in bad.css
$d = [Regex]::Matches($c, '(start)(.*?)(end)') | Select -ExpandProperty Value 

#3. should replace the regex part in bad.css with the whole good.css
if ($d) {
  $c = $c -replace $d, $b
  Set-Content $stylingOverride -Value $c
}

最佳答案

转义提取的字符串,以便与文字(子)字符串匹配:

$c = $c -replace [regex]::Escape($d), $b

或者,使用.Replace()方法代替-replace运算符。前者执行简单的字符串替换,而后者执行正则表达式替换。
$c = $c.Replace($d, $b)

关于regex - “the regular expression pattern is not valid”,同时用数组替换正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42110385/

相关文章:

java - 正则表达式 - 从字符串中提取数字。数字应该是我输入的前 5 位数字

javascript - javascript 中的正则表达式遇到问题

regex - 与Scala中的正则表达式匹配

regex - 正则表达式:txt vs tx?

powershell - 设置通过引用传递的数组变量

windows - 如何获取每个文件的创建时间并格式化

powershell - 在 Azure 自动化 Runbook 中执行时 Set-AzureRmContext 错误

C# 正则表达式 : returning a collection of results

string - 如何将字符串 append 到数据集中的其他字符串?

powershell - PowerShell remove-item成功但抛出异常