繁体   English   中英

Python 正则表达式 - 替换 IP 地址

[英]Python Regex - Replacing IP addresses

我是 python 和正则表达式的新手,我一直试图在 txt 文件中隐藏 IP 地址日志。 我应该避免使用 for 循环和 if 检查 - 如果可能,因为 txt 文件很大(158MB)。

(所有 IP 地址均以 172 开头)

这是我试过的代码:

import re
txt = "test"
x = re.sub(r"^172\.*", "XXX.\", txt)
print(x)

示例 txt 文件:

ABCDEFGHIJKLMNOPRST172.12.65.10RSTUVYZ
ASDG172.56.23.14FSDGHSFSDFDSFHSF
!'^%%&!'+!'+^%&!ÂSDBSDF172.23.23.23SADASFSA
ASGFGD 172.12.23.56 ASDSAFASFDASSADSA

所需的 output:

ABCDEFGHIJKLMNOPRSTXXX.XXX.XXX.XXXRSTUVYZ
ASDGXXX.XX.XX.XXFSDGHSFSDFDSFHSF
!'^%%&!'+!'+^%&!ÂSDBSDFXXX.XXX.XXX.XXXSADASFSA
ASGFGD XXX.XXX.XXX.XXX ASDSAFASFDASSADSA

您确实应该使用re.sub

re.sub("(172)(\.(?:[0-9]{1,3}\.){2}[0-9]{1,3})", r"XXX.XXX.XXX.XXX", tested_addr)

关于正则表达式的解释(您实际上并不需要这些组来满足您的要求,但它是理解正则表达式部分的好方法:

^(172)(\.(?:[0-9]{1,3}\.){2}[0-9]{1,3})$

^ asserts position at start of a line
1st Capturing Group (172)
172 matches the characters 172 literally (case sensitive)
2nd Capturing Group (\.(?:[0-9]{1,3}\.){2}[0-9]{1,3})
\. matches the character . literally (case sensitive)
Non-capturing group (?:[0-9]{1,3}\.){2}
{2} Quantifier — Matches exactly 2 times
Match a single character present in the list below [0-9]{1,3}
{1,3} Quantifier — Matches between 1 and 3 times, as many times as possible, giving back as needed (greedy)
0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
\. matches the character . literally (case sensitive)
Match a single character present in the list below [0-9]{1,3}
{1,3} Quantifier — Matches between 1 and 3 times, as many times as possible, giving back as needed (greedy)
0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
$ asserts position at the end of a line

使用: 172(?:\.\d{1,3}){3}

代码:

string = r'''ABCDEFGHIJKLMNOPRST172.12.65.10RSTUVYZ
ASDG172.56.23.14FSDGHSFSDFDSFHSF
!'^%%&!'+!'+^%&!SDBSDF172.23.23.23SADASFSA
ASGFGD 172.12.23.56 ASDSAFASFDASSADSA'''

print re.sub(r'172(?:\.\d{1,3}){3}', "XXX.XXX.XXX.XXX", string)

Output:

ABCDEFGHIJKLMNOPRSTXXX.XXX.XXX.XXXRSTUVYZ
ASDGXXX.XXX.XXX.XXXFSDGHSFSDFDSFHSF
!'^%%&!'+!'+^%&!SDBSDFXXX.XXX.XXX.XXXSADASFSA
ASGFGD XXX.XXX.XXX.XXX ASDSAFASFDASSADSA

演示和解释

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM