regex - PowerShell 正则表达式不工作

标签 regex windows powershell

我有以下 PowerShell 脚本:

$SCRIPTNAME = "myfile.js"
$SUBJECT = Get-Content $SCRIPTNAME | Out-String
if ($SUBJECT -match ".*/// COMMENT.*?$(.*)")
{
    echo $matches[1];
}
$Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

它生成以下错误(我正在尝试使用正则表达式捕获组,但它不起作用):

.* : The term '.*' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Users\User\Desktop\install.ps1:21 char:39
+ if ($SUBJECT -match ".*/// COMMENT.*?$(.*)")
+                                        ~~
    + CategoryInfo          : ObjectNotFound: (.*:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

为什么第二个捕获组的 .* 部分出现问题?

最佳答案

明白了。我需要用单引号 ' ' 转义正则表达式,并进一步添加单行和多行说明符 (?sm):

$SCRIPTNAME = "myfile.js"
$SUBJECT = Get-Content $SCRIPTNAME | Out-String
if ($SUBJECT -match '(?sm).*/// COMMENT.*?$(.*)' -and $matches.Count -ge 2)
{
    echo $matches[1];
}
$Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

关于regex - PowerShell 正则表达式不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26467117/

相关文章:

java - 使用身份验证从 JAVA 连接到 RServe

powershell - 无法使用 powershell 为 Web 角色启用诊断

powershell - 从另一个PowerShell session 监视PowerShell session 中的作业

regex - 正则表达式只允许数字、逗号和破折号

c++ - 在 C++ 中使用 Boost 正则表达式进入具有特定特征的方括号之间没有得到答案

php - 删除字符串中的两个首词和首词(title wordpress)

Windows Server 2019 Docker docker.exe : Error response from daemon: failed to start service utility VM (createreadwrite):

c# - 在 C# 中使用 Socket 改进 TCP 转发器

powershell - 当karma:interactive运行时,Intellij无法保存文件

python-3.x - 为什么这个正则表达式不匹配任何东西?