我正在尝试使用正则表达式清理一些 html 文件(是的,我看过帖子。我不希望通常解析 html)并且我想删除所有不包含标签的行。我的脚本如下:
Remove-Item $args[1]
$text = (Get-Content -Path $args[0] -Raw)
$text = $text -replace "^\s*\r?\n"
New-Item -Path $args[1] -ItemType File -Force -Value $text
我想替换很多其他东西,但我主要是在尝试修复
我可以验证内部正则表达式是否有效:VSCode(使用 JS 正则表达式而不是 powershell 的 .NET 正则表达式)使用提供的正则表达式正确匹配(并替换)有问题的行。
我知道Powershell 是 Special,所以我将 的输出转换为Get-Content带有嵌入换行符的原始字符串。这没有帮助。
我可以验证其他函数(即remove-itemand new-item)是否工作正常,并且其他正则表达式可以通过将正则表达式文本从"^\s*\r?\n"to更改"p", "abc"并看到p标签都变成abc标签来工作。
此外,正则表达式\s*\r?\n有效,所以并不是正则表达式找不到换行符。
正则表达式\A\s*\r?\n也不起作用,这意味着它与 PowerShell 如何查找字符串的开头\结尾有关。
这是怎么回事?
<p>This is some text</p>
(the next line has a bunch of spaces)
<p>this is some more text</p>
作为参考,当使用 VSCode 的 JS 正则表达式引擎时(我相信类似于 PCRE),我的正则表达式应该(并且确实)匹配上述示例的第二、第四和第五行
最后,反编译正则表达式:
^ from the start of the string
\s* match any number of whitespaces
\r? possibly followed by a carriage return
\n then a newline