gpt4 book ai didi

regex - 协助使用 PowerShell 中的可选正则表达式

转载 作者:行者123 更新时间:2023-12-02 22:56:13 24 4
gpt4 key购买 nike

我正在尝试从如下所示的数据中解析出软件、版本号和安装日期:

AXIS Media Control EmbeddedAXIS Media Control 5.60 Redist  [installed on 2014/05/28]Cisco WebEx MeetingsAdobe Flash Player 13 ActiveX  [version 13.0.0.214]Adobe Flash Player 13 Plugin  [version 13.0.0.214]Bullzip PDF Printer 9.3.0.1516  [version 9.3.0.1516]  [installed on 2014/05/12]Security Management System (Client)  [version 7.0.1.0]  [installed on 2014/05/28]Symmetry7500 Plugin  [version 1.3]  [installed on 2014/05/28]Cross Match Transmission Manager  [version 3.8.9.0012]  [installed on 2014/05/08]Cross Match Live Scan Management System  [version 8.4.5.0031]  [installed on 2014/05/08]System Center Endpoint Protection  [version 4.7.214.0]  [installed on 2016/07/21]Mozilla Firefox 50.0.2 (x86 en-US)  [version 50.0.2]Mozilla Maintenance Service  [version 50.0.2]

The data I'm working will always start with the software name, and then could have both version number and installed on date, or one or the other, or neither. If both are present though it'll always be version number followed by installed on date.

Here's the regex I have so far:

(.*?)  ((\[version .*\])  (\[installed on .*\])|(\[version .*\])|(\[installed on .*\]))

这有效,除非它只是软件的名称。的各种放置?标记正则表达式的 OR 部分无效。我需要进行哪些更改才能捕获项目 1 和 3 以及其他所有内容?

最佳答案

我会使用这样的表达式:

(.+?)(?:  \[version (.+?)\])?(?:  \[installed on (.+?)\])?$

这使用非捕获组来匹配可选部分,并使用非贪婪匹配的捕获组来提取相关信息。

  • (.+?): 抓取组提取软件名。
  • (?:\[version (.+?)\])?:可选的非捕获组将版本信息(如果存在)与用于提取版本号的嵌套捕获组匹配。
  • (?:\[installed on (.+?)\])?:可选的非捕获组将安装日期信息(如果存在)与用于提取日期的嵌套捕获组匹配.
  • $:将表达式锚定在字符串的末尾。

例子:

$file    = 'C:\path\to\software.txt'
$pattern = '(.+?)(?: \[version (.+?)\])?(?: \[installed on (.+?)\])?$'

Get-Content $file | Select-String $pattern | ForEach-Object {
New-Object -Type PSObject -Property @{
Name = $_.Matches.Groups[1].Value
Version = $_.Matches.Groups[2].Value
InstalledOn = $_.Matches.Groups[3].Value
}
}

关于regex - 协助使用 PowerShell 中的可选正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41515672/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com