regex - PowerShell 从脚本中删除所有注释

我正在寻找一种从文件中删除所有评论的方法。有多种评论方式,但我只对简单的 # 感兴趣形成意见。原因是我只使用 <# #>在函数中 .SYNOPSIS这是功能代码,而不仅仅是评论,所以我想保留它们)。

编辑:我已经使用下面有用的答案更新了这个问题。

所以我只需要几个场景:

a) 用 # 整行注释在行首(或者之前可能有空格。即 ^\s*# 的正则表达式似乎有效。

b) 在行首有一些代码,然后在行尾有一个命令。 我想避免剥离线,例如Write-Host "#####"但我认为这已包含在我的代码中。

我能够通过拆分删除行尾注释,因为我不知道如何使用正则表达式来做到这一点,有谁知道用正则表达式实现它的方法吗?

拆分并不理想 <#在一行中将被 -split 删除但我已经通过拆分 " #" 解决了这个问题.这并不完美,但可能已经足够好了 - 也许存在更可靠的正则表达式方式?

当我对我的 7,000 行长脚本执行以下操作时,它有效(!)并删除了大量注释,但是,输出文件的大小几乎翻了一番(!?),从 400kb 到大约 700kb。有谁知道为什么会发生这种情况以及如何防止这种情况发生(它与 BOM 或 Unicode 或类似的东西有关吗?Out-File 似乎真的使文件大小膨胀!)

$x = Get-Content ".\myscript.ps1"   # $x is an array, not a string
$out = ".\myscript.ps1"
$x = $x -split "[\r\n]+"               # Remove all consecutive line-breaks, in any format '-split "\r?\n|\r"' would just do line by line
$x = $x | ? { $_ -notmatch "^\s*$" }   # Remove empty lines
$x = $x | ? { $_ -notmatch "^\s*#" }   # Remove all lines starting with ; including with whitespace before
$x = $x | % { ($_ -split " #")[0] }    # Remove end of line comments
$x = ($x -replace $regex).Trim()       # Remove whitespace only at start and end of line
$x | Out-File $out
# $x | more

最佳答案

老实说,识别和处理所有评论的最佳方法是使用 PowerShell 的语言解析器或 Ast 类之一。抱歉,我不知道哪个 Ast 包含评论;所以这是一种过滤掉 block 注释和行注释的更丑陋的方法。

$code = Get-Content file.txt -Raw
$comments = [System.Management.Automation.PSParser]::Tokenize($code,[ref]$null) |
    Where Type -eq 'Comment' | Select -Expand Content
$regex = ( $comments |% { [regex]::Escape($_) } ) -join '|'

# Output to remove all empty lines
$code -replace $regex -split '\r?\n' -notmatch '^\s*$'

# Output that Removes only Beginning and Ending Blank Lines
($code -replace $regex).Trim()

https://stackoverflow.com/questions/60996992/

相关文章:

java - 从 JSONObject 中删除除一个之外的所有键

spring-boot - 带有 Spring 的 GraphQL-java - 解析器 vd da

scala - 为什么zio的putStrLn没有输出

sql - Oracle FETCH FIRST 1 ROW with UNION ALL 语句

node.js - 如何与 nx 并行运行 express 和 angular?

javascript - 如何生成随机素数?

spring-boot - Spring WebFlux Reactive 和 Kotlin Cor

sql - Postgres : How do I extract year and month f

react-native - 在 React Native Web 的情况下自定义 react-na

java - Optional.ofNullable() 中的空指针异常