PowerShell如何捕获特定模式后的文本字符串,但不将模式本身包含在结果中



我正在尝试从文本文件中提取/捕获特定文本模式之后的所有7个字符的字母数字字符串。我得到了7个字符的字符串,但我也得到了其他我不需要的"模式"字符。我是regex和PowerShell的新手,在这里发帖之前我真的试过了。

以下是文本文件的样子:

{"hash":"hvwRn2V","title":"","description":null,"has_sound":false,"width":1920,"height":1080,"size":444751,"ext":".jpg","animated":false,"prefer_video":false,"looping":false,"datetime":"2016-02-08 09:27:18","edited":"0"},{"hash":"GakvoVT","title":"","description":null,"has_sound":false,"width":1920,"height":1080,"size":189987,"ext":".jpg","animated":false,"prefer_video":false,"looping":false,"datetime":"2016-02-08 09:27:14","edited":"0"},{"hash":"bn0lqId","title":"","description":null,"has_sound":false,"width":1920,"height":1080,"size":466105,"ext":".jpg","animated":false,"prefer_video":false,"looping":false,"datetime":"2016-02-08 09:27:11","edited":"0"},

我需要获取位于两个双引号之间的所有7个字符的字符串,但前提是它们位于hash":之后。从上面的文本中,我需要从hash":"hvwRn2V"中获得hvwRn2V,依此类推

我正在使用这个PowerShell代码,它很有效,但它也在结果中给了我我不想要的模式文本hash":

$input_path = 'C:UsersJacktextfile.txt'
$output_file = 'C:UsersJackoutput.txt'
$regex = 'hash":"([a-zA-Z_0-9]){7}'
Select-String -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file

我得到的是:

hash":"hvwRn2V
hash":"GakvoVT
hash":"bn0lqId

我做错了什么?

提前感谢您的帮助。

您需要用捕获圆括号包装7个字符的模式,并将$_.Groups[1].Value写入输出文件:

$input_path = 'C:UsersJacktextfile.txt'
$output_file = 'C:UsersJackoutput.txt'
$regex = 'hash":"([a-zA-Z0-9_]{7})"'
Select-String -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Groups[1].Value } > $output_file

注意,我还在模式末尾添加了",以确保提取的值正好是双引号内的7个字符的字符串。

该文本是json。如果将文本括在方括号[]中,它将是一个对象数组。打印出每个对象中的哈希属性,如下所示:

cat file.json | convertfrom-json | % hash
hvwRn2V
GakvoVT
bn0lqId

最新更新