gpt4 book ai didi

regex - 使用正则表达式从 .log 文件中提取数据

转载 作者:行者123 更新时间:2023-12-04 21:02:47 26 4
gpt4 key购买 nike

我正在尝试使用正则表达式正向后视提取数据。我创建了一个包含以下内容的 .ps1 文件:

$input_path = ‘input.log’

$output_file = ‘Output.txt’

$regex = ‘(?<= "name": ")(.*)(?=",)|(?<= "fullname": ")(.*)(?=",)|(?<=Start identity token validation\r\n)(.*)(?=ids: Token validation success)|(?<= "ClientName": ")(.*)(?=",\r\n "ValidateLifetime": false,)’

select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } >$output_file

输入文件如下所示:
08:15.27.47-922: T= 11 ids: Start end session request
08:15.27.47-922: T= 11 ids: Start end session request validation
08:15.27.47-922: T= 11 ids: Start identity token validation
08:15.27.47-922: T= 11 ids: Token validation success
{
"ClientId": "te_triouser",
"ClientName": "TE Trio User",
"ValidateLifetime": false,
"Claims": {
"iss": "http://sv-trio17.adm.linkoping.se:34000/core/",
"aud": "te_triouser",
"exp": "1552054900",
"nbf": "1552054600",
"nonce": "f1ae9044-25f9-4e7f-b39f-bd7bdcb9dc8d",
"iat": "1552054600",
"at_hash": "Wv_7nNe42gUP945FO4p0Wg",
"sid": "9870230d92cb741a8674313dd11ae325",
"sub": "23223",
"auth_time": "1551960154",
"idp": "tecs",
"name": "tele2",
"canLaunchAdmin": "1",
"isLockedToCustomerGroup": "0",
"customerGroupId": "1",
"fullname": "Tele2 Servicekonto Test",
"tokenIdentifier": "2Ljta5ZEovccNlab9QXb8MPXOqaBfR6eyKst/Dc4bF4=",
"tokenSequence": "bMKEXP9urPigRDUguJjvug==",
"tokenChecksum": "NINN0DDZpx7zTlxHqCb/8fLTrsyB131mWoA+7IFjGhAV303///kKRGQDuAE6irEYiCCesje2a4z47qvhEX22og==",
"idpsrv_lang": "sv-SE",
"CD_UserInfo": "23223 U2 C1",
"amr": "optional"
}
}

如果我通过 http://regexstorm.net/tester 运行正则表达式我得到了正确的匹配。但是当我在我的计算机上使用 powershell 运行我的脚本时,我没有在正则表达式问题中获得\r\n 的匹配项。我只从前两个正则表达式问题中获得匹配项。

最佳答案

  • 我同意@AdminOfThings 将 Get-Content 与 -raw 一起使用范围。
  • 也不要在脚本中使用打印引号。
  • 如果前导空格的数量不是真正固定的,请替换为一个空格和 +*量词。
  • 制作 \r可选 => \r? .

  • 一个 minimal complete verifiable example还应包括您的预期输出。

    EDIT 将 Regex 更改为更好的可读性

    下面的脚本
    ## Q:\Test\2019\03\22\SO_55298614.ps1

    $input_path = 'input.log'
    $output_file = 'Output.txt'

    $regexes = ('(?<= *"(full)?name": ")(.*)(?=",)',
    '(?<=Start identity token validation\r?\n)(.*)(?=ids: Token validation success)',
    '(?<= *"ClientName": ")(.*)(?=",\r?\n *"ValidateLifetime": false,)')

    $regex = [RegEx]($regexes -join'|')


    Get-Content $input_path -Raw | Select-String -pattern $regex -AllMatches |
    ForEach-Object { $_.Matches.Value }

    产生这个样本输出:
    > Q:\Test\2019\03\22\SO_55298614.ps1
    08:15.27.47-922: T= 11
    TE Trio User
    tele2
    Tele2 Servicekonto Test

    关于regex - 使用正则表达式从 .log 文件中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55298614/

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