PowerShell 正则表达式不起作用 [英] PowerShell regex not working
本文介绍了PowerShell 正则表达式不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下 PowerShell 脚本:
I have the following PowerShell script:
$SCRIPTNAME = "myfile.js"
$SUBJECT = Get-Content $SCRIPTNAME | Out-String
if ($SUBJECT -match ".*/// COMMENT.*?$(.*)")
{
echo $matches[1];
}
$Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
它产生以下错误(我正在尝试使用正则表达式捕获组,但它不起作用):
It is generating the following error (I'm trying to use regex capture groups, but its not working):
.* : 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
为什么第二个捕获组的 .*
部分有问题?
Why is it having issues with the .*
part of the second capture group?
推荐答案
明白了.我需要用单引号 '
'
转义正则表达式,并进一步添加单行和多行说明符 (?sm)
:
Got it. I needed to escape the regular expression with single quotes '
'
, and furthermore add single and multiline specifiers (?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');
这篇关于PowerShell 正则表达式不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文