Python 正则表达式搜索和sub
我想找到一种更快的方法,用字符串kittycat替换每个用户名Python 正则表达式搜索和sub,python,regex,Python,Regex,我想找到一种更快的方法,用字符串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_
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.
(正则表达式假设没有用户名包含“:”)
__我的当前解决方案
import re
regex = '^.+Auditing\:\s+(?P<username>.+?(?=\:))'
result = re.search(regex, string)
username = result.group('username')
result=re.sub(username,kittycat,string)
print result
重新导入
正则表达式='^.+审计\:\s+(?P.+?(?=\:)'
结果=重新搜索(正则表达式,字符串)
username=result.group('username')
result=re.sub(用户名、kittycat、字符串)
打印结果
您可以使用
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.
见
图案细节
-捕获组1:(审核:\s*)
子字符串,然后是0+空格审核:
-捕获组2:除([^::]+)
之外的一个或多个字符:
在替换lambda表达式中,组1用
m.Group(1)
表示,组2值用m.Group(2)
表示,为什么使用re.search
re.sub(r'(审计:\s*)[^:::+',r'\1{}'。格式(kittycat),s)
。如果kittycat
只是一个字符串,而不是一个变量,那么替换就更简单了:r'\1kittycat'
re.sub(r')(?感谢您的快速回复。如果我想对用户名r'\1{}进行哈希运算,该怎么办?。格式(lambda m:hashlib.sha512(m.group().encode()).hexdigest()),s)”将是您不需要的输出,r'\1{}“.
then.re.sub(r'(审计:\s*)([^::+]),lambda m:m.group(1)+hashlib.sha512(m.group(2.encode()).hexdigest(),s)
。