gpt4 book ai didi

python - 正则表达式搜索和子

转载 作者:行者123 更新时间:2023-12-01 08:52:56 26 4
gpt4 key购买 nike

我想找到一种更快的方法来用字符串 kittycat 替换每个用户名。

2018 Aug 01 01:59:59 WinEvtLog: Security: AUDIT_FAILURE(4625): Microsoft-Windows-Security-Auditing: peter.parker: no domain: my.own.domain: An account failed to log on.

2018 Aug 02 01:59:59 WinEvtLog: Security: AUDIT_SUCCESS(4624): Microsoft-Windows-Security-Auditing: 4dministr4t0r: my-log: still.my.domain: An account was successfully logged on.

2018 Aug 03 01:59:59 WinEvtLog: Security: AUDIT_FAILURE(4768): Microsoft-Windows-Security-Auditing: (no user): no domain: my.other.domain: A Kerberos authentication ticket (TGT) was requested.

(正则表达式假设 - 没有用户名包含“:”)

__My_Current_Solution

import re

regex = '^.+Auditing\:\s+(?P<username>.+?(?=\:))'
result = re.search(regex, string)
username = result.group('username')
result=re.sub(username,kittycat,string)
print result

最佳答案

您可以使用

import re, hashlib
s = "2018 Aug 01 01:59:59 WinEvtLog: Security: AUDIT_FAILURE(4625): Microsoft-Windows-Security-Auditing: peter.parker: no domain: my.own.domain: An account failed to log on."
print(re.sub(r'(Auditing:\s*)([^:]+)', lambda m: m.group(1) + hashlib.sha512(m.group(2).encode()).hexdigest(), s))
# => 2018 Aug 01 01:59:59 WinEvtLog: Security: AUDIT_FAILURE(4625): Microsoft-Windows-Security-Auditing: 2dd95ce5e79de5cedbb3f50b635b9b9125c19464b15938a242aec0db227cfb408570837b12912db97704cac96d22d9fda9f140ea63adf17959c334570ccc8a41: no domain: my.own.domain: An account failed to log on.

请参阅Python demo

图案详细信息

  • (Auditing:\s*) - 捕获组 1:Auditing: 子字符串,然后是 0+ 空格
  • ([^:]+) - 捕获组 2:除 : 之外的一个或多个字符。

在替换 lambda 表达式中,组 1 使用 m.group(1) 引用,组 2 值使用 m.group(2) 引用。

关于python - 正则表达式搜索和子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52990033/

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