【发布时间】:2014-12-15 12:31:45
【问题描述】:
我有以下 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
为什么第二个捕获组的 .* 部分有问题?
【问题讨论】:
-
您前面有一个行尾锚
$,这可能会导致问题。如果您想要文字$则将其转义或将其移至模式的末尾。 -
@arco444 我试过用
\$代替,但这仍然会产生同样的错误。 -
您可能遇到的另一个问题是 PowerShell 会将其评估为子表达式
$(.*),这也会导致错误。在整个字符串上使用单引号可以解决这个问题。如果您仍然无法向我们展示一些示例数据和所需的输出,这将有助于社区解决您的问题。 -
你需要添加 (?sm)
-
使用名为matched的powershell会更好。 link 基本上是
(?<Text>.*)。然后你会得到$matches.Text
标签: regex windows powershell