【发布时间】:2021-12-14 01:53:23
【问题描述】:
我正在尝试使用正则表达式清理一些 html 文件(是的,我见过 the post。我一般不打算解析 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 is Special,所以我将Get-Content 的输出转换为带有嵌入换行符的原始字符串。这没有帮助。
我可以通过将正则表达式文本从 "^\s*\r?\n" 更改为 "p", "abc" 并看到 p 标记来验证其他函数(即 remove-item 和 new-item)工作正常,并且其他正则表达式工作正常都变成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
【问题讨论】:
标签: html regex powershell