我有以下 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/