PowerShell 解析

PowerShell parsing

我从 Git 日志中得到以下输入:

Merge: d9335ae 7d12d50
Author: name\name <mail@mail.com>
Date:   Wed Oct 31 12:55:00 2018 -0500

id:202847 Merge branch 'release/2.6.0' into release/3.0.0

# Conflicts:
#   configuration/path/path

我需要解析 id:xxxxx,然后将该 ID 传递给目标进程 API,其中 returns ID 名称。

我有一个自定义 PowerShell 函数可以完成此操作。

我需要帮助的是将其组合到一个执行此操作的 PowerShell 函数中。我匹配 id 的正则表达式是一个简单的 id:\d+.

我想要的结果是如下所示的输出(ID 后面的文本是从目标进程返回的内容):

TP Id:202847 Professional Lines: 2,800,000 Policy Aggregate Limit update

PowerShell 具有非常强大的本机正则表达式支持,您可以像这样从 Git 命令中轻松检索 ID 值。我们首先捕获您的 git 命令的输出(在我的例子中,我将其粘贴到一个变量中,但您也可以 运行 $CommitMsg = git commit 202847 以另一种方式将输出捕获到一个变量中: )

$r="Merge: d9335ae 7d12d50
Author: name\name <mail@mail.com>
Date:   Wed Oct 31 12:55:00 2018 -0500

id:202847 Merge branch 'release/2.6.0' into release/3.0.0

# Conflicts:
#   configuration/path/path"

接下来,我使用 PowerShell 正则表达式加速器 ([regex]PowerShell has lots of useful accelerators!) 在变量 $r 中查找正则表达式模式 id:.....\w+ 的匹配项,它查找以 id: 开头并在其后有六个字符的字符串,然后是白色的 space.

[regex]::Match($r, "id:(.....)\w+").Value
>id:202847

您可以像这样将输出存储在变量中:

$CommitID = [regex]::Match($r, "id:(.....)\w+").Value

然后使用字符串扩展将其嵌入到您的其他命令中,如下所示:

"TP $CommitID Professional Lines: 2,800,000 Policy Aggregate Limit update"
>TP Id:202847 Professional Lines: 2,800,000 Policy Aggregate Limit update

提供更符合 PowerShell 习惯的替代方案:

# Sample log text (multi-line string in the form of a here-string).
$logText = @'
Merge: d9335ae 7d12d50
Author: name\name <mail@mail.com>
Date:   Wed Oct 31 12:55:00 2018 -0500

id:202847 Merge branch 'release/2.6.0' into release/3.0.0

# Conflicts:
#   configuration/path/path
'@

# Extract the ID number alone, via a capture group `(...)`, using the
# -match regex operator and the automatic $Matches variable that reflects the 
# results.
# Entry 1 of $Matches contains the 1st (and here only) capture-group value.
# \b is used to make the regex more robust, by only matching at word boundaries.
# With the sample input, $id receives value '202847'
$id = if ($logText -match '\bid:(\d+)\b') { $Matches[1] }

# Note: If your input comes directly from a *file*, say 'commit.log', 
#       use the following command instead:
#
#  $id = (Select-String -list '\bid:(\d+)\b' commit.log).Matches.Groups[1].Value
#
# Alternatively, if reading the whole file into memory at once is acceptable,
# pass (Get-Content -Raw commit.log) instead of $logText to -match.

# Build the desired output string from the ID obtained and the API return value.
"TP Id:$id " + $returnValFromApi