在下面的代码中,我试图用保存正确代码的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/