簡體   English   中英

在Powershell中從字符串中提取字符串

[英]Extracting strings from String in Powershell

我有一個long string: its a teamcity buildLog這是一個來自 teamcity 的 buildLog。

[11:27:30] :     [Step 5/5] 15:27:30 INFO: Average times: total 0.455, latency 0.455, connect 0.004
[11:27:30] :     [Step 5/5] 15:27:30 INFO: Percentiles:
[11:27:30] :     [Step 5/5] +---------------+---------------+
[11:27:30] :     [Step 5/5] | Percentile, % | Resp. Time, s |
[11:27:30] :     [Step 5/5] +---------------+---------------+
[11:27:30] :     [Step 5/5] |           0.0 |         0.021 |
[11:27:30] :     [Step 5/5] |          50.0 |         0.103 |
[11:27:30] :     [Step 5/5] |          90.0 |         1.166 |
[11:27:30] :     [Step 5/5] |          95.0 |          2.27 |
[11:27:30] :     [Step 5/5] |          99.0 |          2.77 |
[11:27:30] :     [Step 5/5] |          99.9 |         6.996 |
[11:27:30] :     [Step 5/5] |         100.0 |        10.312 |
[11:27:30] :     [Step 5/5] +---------------+---------------+
[11:27:30] :     [Step 5/5] 15:27:30 INFO: Request label stats:
[11:27:30] :     [Step 5/5] +------------------------------------------+--------+---------+--------+-------------+
[11:27:30] :     [Step 5/5] | label                                    | status |    succ | avg_rt | error       |
[11:27:30] :     [Step 5/5] +------------------------------------------+--------+---------+--------+-------------+
[11:27:30] :     [Step 5/5] | Activity History                         |   OK   | 100.00% |  1.608 |             |
[11:27:30] :     [Step 5/5] | Asset Allocation                         |   OK   | 100.00% |  0.100 |             |
[11:27:30] :     [Step 5/5] | Dashboard Cards and Employee Information |   OK   | 100.00% |  0.255 |             |
[11:27:30] :     [Step 5/5] | Fund Details                             |   OK   | 100.00% |  0.825 |             |
[11:27:30] :     [Step 5/5] | Investments                              |   OK   | 100.00% |  0.132 |             |
[11:27:30] :     [Step 5/5] | Minimum Version                          |   OK   | 100.00% |  0.032 |             |
[11:27:30] :     [Step 5/5] | Rate of Return                           |   OK   | 100.00% |  0.047 |             |
[11:27:30] :     [Step 5/5] | Retirement Outlook Card                  |   OK   | 100.00% |  1.166 |             |
[11:27:30] :     [Step 5/5] | Retirement Outlook Full                  |   OK   | 100.00% |  1.160 |             |
[11:27:30] :     [Step 5/5] | Savings Rate                             |   OK   | 100.00% |  0.112 |             |
[11:27:30] :     [Step 5/5] | Secure Auth Login                        |  FAIL  |  98.58% |  0.207 | Bad Request |
[11:27:30] :     [Step 5/5] | Validate Savings Rate Change             |   OK   | 100.00% |  0.127 |             |
[11:27:30] :     [Step 5/5] | Vested Balance                           |   OK   | 100.00% |  0.157 |             |
[11:27:30] :     [Step 5/5] +------------------------------------------+--------+---------+--------+-------------+
[11:27:35] :     [Step 5/5] 15:27:35 INFO: Ending data feeding...
[11:27:36] :     [Step 5/5] 15:27:36 INFO: Online report link: https://a.blazemeter.com/app/#/masters/36669958

從上面的構建日志中,我必須獲取Percentiles TableRequest Label Stats table 和Online Report Link

我嘗試了下面的代碼,但它沒有返回:

$firststring = "Percentiles:"
$secondstring = "Request label stats:"
$pattern =  "$firststring(.*?)$secondstring"
$result = [regex]::Match($file,$pattern).Groups[1].Value
$result >> returns none

和下面的代碼來獲取字符串。

$Regex = [Regex]::new("(?<=Percentiles:)(.*)(?=Request label stats:)")
$Match = $Regex.Match($status)
if($Match.Success)
{
  $Match.Value
}

這也沒有返回。 任何幫助將非常感激。

我無法為您檢查 PowerShell 3.0。 但以下內容適用於 Windows PowerShell 5.1。 我有兩種解決方案,一種包括作為比賽一部分的第一個信息行,另一種不包括。

# Set up your strings to look for
$firststring = [regex]::Escape("Percentiles:")
$secondstring = [regex]::Escape("Request label stats:")

# Pattern which includes the line with $firststring
$withInfoPattern = ".*$firststring(.*\n)*(?=.*$secondstring)"

# Pattern which omits the line with $firststring
$withoutInfoPattern = "(?<=$firststring\s+)(.*\n)*(?=.*$secondstring)"

# We will use $withInfoPattern in this example but you could also use $withoutInfoPattern
# This assumes your content string is in a variable called $content
$matchedContent = if( $content -match $withInfoPattern ) {
  $matches[0]
}

這顯示了如何匹配您的第一個案例Percentiles表數據。 要獲取第二個表格和報告鏈接,您應該能夠使用上面的代碼和下面的解釋來提取這些數據以及學習練習。

此時$matchedContent將包含您正在尋找的輸出。 如果您不希望返回匹配的第一行,您也可以使用$withoutInfoPattern進行匹配。 我將在下面解釋這一點:

  • 雖然在這種情況下不是必需的,但通過[regex]::Escape(string)將要插入到正則表達式模式中的字符串放入是一種很好的做法。 這是一個很好的做法,可以防止您將來無意中忘記使用特殊的正則表達式字符轉義字符串。
  • $withInfoPattern匹配$firststring前面有或沒有字符的任何行。 $withoutInfoPattern而是使用積極的后視來確保在發生$firstString匹配的$firstString
  • (.*\\n)*使用捕獲組來匹配任何字符或不匹配字符(這就是.*意思),后跟換行符。 默認情況下,換行符不與. 並且無法使用-match運算符更改此行為。 尾隨*查找前面捕獲組的任何實例或不查找任何實例。
    • -match通常不會跨換行匹配。 以這種方式使用(.*\\n)*可以繞過該限制。
  • (?=.*$secondString)是一個正向前瞻,以確保模式主模式在前瞻中指定的模式之前。 .*$secondString將從該行的開頭開始匹配,因此我們在該行中查找后跟$secondString任何字符。
  • 調用-match運算符來查找$withInfoPattern (或$withoutInfoPattern內) $content 這假設您要搜索的字符串作為字符串存儲在名為$content的變量中(不是默認情況下Get-Content將執行的字符串數組。
    • 您可以使用$content = Get-Content -Raw將文件作為帶有換行符的單個字符串讀取,或者在匹配之前將$content數組與換行符連接起來: $content -join "`n"
  • -match將返回$true$false 如果$true ,您可以從第一個索引中的自動變量$matches中獲取匹配的內容。 由於數組使用從零開始的索引,這會轉化為$matches[0]

其他正則表達式提示

我強烈建議使用站點https://regexr.com/來測試您的表達式。雖然這僅支持 JavaScript 和 PCRE 引擎,但兩者都足夠接近 .NET 正則表達式引擎,因此通常不會出現問題。 即使您發現某些表達式不起作用,它也很好地解釋了不同的正則表達式標記,並且在您開發表達式時,它會在底部窗格中解釋每個字符序列的含義。

一旦你有了正則表達式模式,你就可以使用switch來運行日志行並從你的表中構建對象。 下面我將其分解為單獨的功能。

$log = @'
[11:27:30] :     [Step 5/5] 15:27:30 INFO: Average times: total 0.455, latency 0.455, connect 0.004
[11:27:30] :     [Step 5/5] 15:27:30 INFO: Percentiles:
[11:27:30] :     [Step 5/5] +---------------+---------------+
[11:27:30] :     [Step 5/5] | Percentile, % | Resp. Time, s |
[11:27:30] :     [Step 5/5] +---------------+---------------+
[11:27:30] :     [Step 5/5] |           0.0 |         0.021 |
[11:27:30] :     [Step 5/5] |          50.0 |         0.103 |
[11:27:30] :     [Step 5/5] |          90.0 |         1.166 |
[11:27:30] :     [Step 5/5] |          95.0 |          2.27 |
[11:27:30] :     [Step 5/5] |          99.0 |          2.77 |
[11:27:30] :     [Step 5/5] |          99.9 |         6.996 |
[11:27:30] :     [Step 5/5] |         100.0 |        10.312 |
[11:27:30] :     [Step 5/5] +---------------+---------------+
[11:27:30] :     [Step 5/5] 15:27:30 INFO: Request label stats:
[11:27:30] :     [Step 5/5] +------------------------------------------+--------+---------+--------+-------------+
[11:27:30] :     [Step 5/5] | label                                    | status |    succ | avg_rt | error       |
[11:27:30] :     [Step 5/5] +------------------------------------------+--------+---------+--------+-------------+
[11:27:30] :     [Step 5/5] | Activity History                         |   OK   | 100.00% |  1.608 |             |
[11:27:30] :     [Step 5/5] | Asset Allocation                         |   OK   | 100.00% |  0.100 |             |
[11:27:30] :     [Step 5/5] | Dashboard Cards and Employee Information |   OK   | 100.00% |  0.255 |             |
[11:27:30] :     [Step 5/5] | Fund Details                             |   OK   | 100.00% |  0.825 |             |
[11:27:30] :     [Step 5/5] | Investments                              |   OK   | 100.00% |  0.132 |             |
[11:27:30] :     [Step 5/5] | Minimum Version                          |   OK   | 100.00% |  0.032 |             |
[11:27:30] :     [Step 5/5] | Rate of Return                           |   OK   | 100.00% |  0.047 |             |
[11:27:30] :     [Step 5/5] | Retirement Outlook Card                  |   OK   | 100.00% |  1.166 |             |
[11:27:30] :     [Step 5/5] | Retirement Outlook Full                  |   OK   | 100.00% |  1.160 |             |
[11:27:30] :     [Step 5/5] | Savings Rate                             |   OK   | 100.00% |  0.112 |             |
[11:27:30] :     [Step 5/5] | Secure Auth Login                        |  FAIL  |  98.58% |  0.207 | Bad Request |
[11:27:30] :     [Step 5/5] | Validate Savings Rate Change             |   OK   | 100.00% |  0.127 |             |
[11:27:30] :     [Step 5/5] | Vested Balance                           |   OK   | 100.00% |  0.157 |             |
[11:27:30] :     [Step 5/5] +------------------------------------------+--------+---------+--------+-------------+
[11:27:35] :     [Step 5/5] 15:27:35 INFO: Ending data feeding...
[11:27:36] :     [Step 5/5] 15:27:36 INFO: Online report link: https://a.blazemeter.com/app/#/masters/36669958
'@ -split '\r?\n'

function get-percentiles {
    param()
    $headerPattern = '\| Percentile'
    $endPattern = '^[^|+]*$'
    $inTable = $false
    switch -regex ($log) {
        $headerPattern {
            $inTable = $true
            continue
        }
        $endPattern {
            if ($inTable) { break } else { continue }
        }
        '\|([^|]+)\|([^|]+).*$' {
            if ($inTable) {
                [PSCustomObject]@{
                    Percentile = $Matches[1].Trim()
                    Time       = $Matches[2].Trim()
                }
            }
        }
    }
}

function get-labeltable {
    param()
    $headerPattern = '\| label'
    $endPattern = '^[^|+]*$'
    $inTable = $false
    switch -regex ($log) {
        $headerPattern {
            $inTable = $true
            continue
        }
        $endPattern {
            if ($inTable) { break } else { continue }
        }
        '\|([^|]+)\|([^|]+)\|([^|]+)\|([^|]+)\|([^|]+).*$' {
            if ($inTable) {
                [PSCustomObject]@{
                    Label  = $Matches[1].Trim()
                    Status = $Matches[2].Trim()
                    Succ   = $Matches[3].Trim()
                    AvgRT  = $Matches[4].Trim()
                    Error  = $Matches[5].Trim()
                }
            }
        }
    }
}

get-percentiles | Format-Table
get-labeltable | Format-Table

輸出

Percentile Time
---------- ----
0.0        0.021
50.0       0.103
90.0       1.166
95.0       2.27
99.0       2.77
99.9       6.996
100.0      10.312


Label                                    Status Succ    AvgRT Error
-----                                    ------ ----    ----- -----
Activity History                         OK     100.00% 1.608
Asset Allocation                         OK     100.00% 0.100
Dashboard Cards and Employee Information OK     100.00% 0.255
Fund Details                             OK     100.00% 0.825
Investments                              OK     100.00% 0.132
Minimum Version                          OK     100.00% 0.032
Rate of Return                           OK     100.00% 0.047
Retirement Outlook Card                  OK     100.00% 1.166
Retirement Outlook Full                  OK     100.00% 1.160
Savings Rate                             OK     100.00% 0.112 
Secure Auth Login                        FAIL   98.58%  0.207 Bad Request
Validate Savings Rate Change             OK     100.00% 0.127
Vested Balance                           OK     100.00% 0.157

我知道這個問題已經得到了回答,但這是我的兩分錢:

$log = @"
[11:27:30] :     [Step 5/5] 15:27:30 INFO: Average times: total 0.455, latency 0.455, connect 0.004
[11:27:30] :     [Step 5/5] 15:27:30 INFO: Percentiles:
[11:27:30] :     [Step 5/5] +---------------+---------------+
[11:27:30] :     [Step 5/5] | Percentile, % | Resp. Time, s |
[11:27:30] :     [Step 5/5] +---------------+---------------+
[11:27:30] :     [Step 5/5] |           0.0 |         0.021 |
[11:27:30] :     [Step 5/5] |          50.0 |         0.103 |
[11:27:30] :     [Step 5/5] |          90.0 |         1.166 |
[11:27:30] :     [Step 5/5] |          95.0 |          2.27 |
[11:27:30] :     [Step 5/5] |          99.0 |          2.77 |
[11:27:30] :     [Step 5/5] |          99.9 |         6.996 |
[11:27:30] :     [Step 5/5] |         100.0 |        10.312 |
[11:27:30] :     [Step 5/5] +---------------+---------------+
[11:27:30] :     [Step 5/5] 15:27:30 INFO: Request label stats:
[11:27:30] :     [Step 5/5] +------------------------------------------+--------+---------+--------+-------------+
[11:27:30] :     [Step 5/5] | label                                    | status |    succ | avg_rt | error       |
[11:27:30] :     [Step 5/5] +------------------------------------------+--------+---------+--------+-------------+
[11:27:30] :     [Step 5/5] | Activity History                         |   OK   | 100.00% |  1.608 |             |
[11:27:30] :     [Step 5/5] | Asset Allocation                         |   OK   | 100.00% |  0.100 |             |
[11:27:30] :     [Step 5/5] | Dashboard Cards and Employee Information |   OK   | 100.00% |  0.255 |             |
[11:27:30] :     [Step 5/5] | Fund Details                             |   OK   | 100.00% |  0.825 |             |
[11:27:30] :     [Step 5/5] | Investments                              |   OK   | 100.00% |  0.132 |             |
[11:27:30] :     [Step 5/5] | Minimum Version                          |   OK   | 100.00% |  0.032 |             |
[11:27:30] :     [Step 5/5] | Rate of Return                           |   OK   | 100.00% |  0.047 |             |
[11:27:30] :     [Step 5/5] | Retirement Outlook Card                  |   OK   | 100.00% |  1.166 |             |
[11:27:30] :     [Step 5/5] | Retirement Outlook Full                  |   OK   | 100.00% |  1.160 |             |
[11:27:30] :     [Step 5/5] | Savings Rate                             |   OK   | 100.00% |  0.112 |             |
[11:27:30] :     [Step 5/5] | Secure Auth Login                        |  FAIL  |  98.58% |  0.207 | Bad Request |
[11:27:30] :     [Step 5/5] | Validate Savings Rate Change             |   OK   | 100.00% |  0.127 |             |
[11:27:30] :     [Step 5/5] | Vested Balance                           |   OK   | 100.00% |  0.157 |             |
[11:27:30] :     [Step 5/5] +------------------------------------------+--------+---------+--------+-------------+
[11:27:35] :     [Step 5/5] 15:27:35 INFO: Ending data feeding...
[11:27:36] :     [Step 5/5] 15:27:36 INFO: Online report link: https://a.blazemeter.com/app/#/masters/36669958

"@

# first parse out the link
$link = ([regex]'(?m)Online report link:\s(.*)$').Match($log).Groups[1].Value

# next remove all except the tables themselves and split into separate lines
$log = $log -replace '(?m)^[^|+]+' -split '\r?\n'

# create two List objects to capture the tables as PsObjects
$percentList = [System.Collections.Generic.List[object]]::new()
$requestList = [System.Collections.Generic.List[object]]::new()

# use switch to loop over the lines
$percentTable = $requestTable = $false
switch -Regex ($log) {
    '^\|\s(Percentile|label)'  { 
        $percentTable = ($matches[1] -eq 'Percentile')
        $requestTable = !$percentTable
        $headers = ($_.Trim("|") -split '\|').Trim()
        continue
    }
    '^\|.*\|$' {
        $tempHash = [ordered]@{}
        $values = ($_.Trim("|") -split '\|').Trim()
        for ($i = 0; $i -lt $headers.Count; $i++) {
            $tempHash[$headers[$i]] = $values[$i]
        }
        if ($percentTable) { 
            $percentList.Add([PscustomObject]$tempHash) 
        } 
        else { 
            $requestList.Add([PscustomObject]$tempHash)
        }
    }
}

# show what we have on screen
$percentList | Format-Table -AutoSize
$requestList | Format-Table -AutoSize
$link

輸出:

Percentile, % Resp. Time, s
------------- -------------
0.0           0.021        
50.0          0.103        
90.0          1.166        
95.0          2.27         
99.0          2.77         
99.9          6.996        
100.0         10.312       



label                                    status succ    avg_rt error      
-----                                    ------ ----    ------ -----      
Activity History                         OK     100.00% 1.608             
Asset Allocation                         OK     100.00% 0.100             
Dashboard Cards and Employee Information OK     100.00% 0.255             
Fund Details                             OK     100.00% 0.825             
Investments                              OK     100.00% 0.132             
Minimum Version                          OK     100.00% 0.032             
Rate of Return                           OK     100.00% 0.047             
Retirement Outlook Card                  OK     100.00% 1.166             
Retirement Outlook Full                  OK     100.00% 1.160             
Savings Rate                             OK     100.00% 0.112             
Secure Auth Login                        FAIL   98.58%  0.207  Bad Request
Validate Savings Rate Change             OK     100.00% 0.127             
Vested Balance                           OK     100.00% 0.157             


https://a.blazemeter.com/app/#/masters/36669958

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM