使用PowerShell在模式之后获取字符串值

时间:2016-07-14 14:18:25

标签: powershell

我想获取html代码段中$ctrl之后的字符串:

 <div ng-if="$ctrl.CvReportModel.IsReady">
                              ng-click="$ctrl.confirmation()"></cs-page-btn>
                 <cs-field field="$ctrl.CvReportModel.Product" ng-model="$ctrl.UploadedFile.Product"></cs-field>
                 <cs-field field="$ctrl.CvReportModel.Month" ng-model="$ctrl.UploadedFile.Month"></cs-field>

所以我想尝试输出:

CvReportModel.IsReady
confirmation()
CvReportModel.Product
CvReportModel.Month

我正在尝试使用Get-ContentSelect-String,但仍然无法获得所需的输出。

1 个答案:

答案 0 :(得分:4)

使用Get-Content cmdlet读取您的文件,并使用regex获取所需内容:

$content = Get-Content 'your_file_path' -raw
$matches = [regex]::Matches($content, '"\$ctrl\.([^"]+)')
$matches | ForEach-Object {
    $_.Groups[1].Value
}

<强>正则表达式:

"\$ctrl\.[^"]+

Regular expression visualization

<强>输出:

CvReportModel.IsReady
confirmation()
CvReportModel.Product
UploadedFile.Product
CvReportModel.Month
UploadedFile.Month

另一种使用Select-String cmdlet和regex具有正面lookbehind的方法:

Select-String -Path $scripts.tmp -Pattern '(?<=\$ctrl\.)[^"]+' | 
    ForEach-Object { $_.Matches.Value }

<强>输出:

CvReportModel.IsReady
confirmation()
CvReportModel.Product
CvReportModel.Month

注意: 这只会返回每行的第一个 $ctrl.*匹配。但是,由于这符合您所需的输出,因此对您来说非常有用。