[英]Only match IP addresses and not other numbers
I want the following regex code to return an output of IP addresses without returning other number values as IP from the source file.我希望以下正则表达式代码返回 IP 地址的 output,而不从源文件返回其他数值作为 IP。
The Code:编码:
import re
logdata = 146.204.224.152 - feest6811 [21/Jun/2019:15:45:24 -0700] "POST /incentivize HTTP/1.1" 302 4622
for item in re.finditer("(?P<host>[\d.]+)", logdata):
print(item.groupdict())
Required output:所需 output:
{'host': '146.204.224.152'}
Unwanted output:不需要的 output:
{'host': '6811'}
I think this should do it:我认为应该这样做:
(?P<host>(\d+\.){3}\d+)
Use利用
import re
logdata = r'146.204.224.152 - feest6811 [21/Jun/2019:15:45:24 -0700] "POST /incentivize HTTP/1.1" 302 4622'
for item in re.finditer(r"\b(?P<host>(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})\b", logdata):
print(item.groupdict())
See Python proof .参见Python 证明。
Results : {'host': '146.204.224.152'}
.结果:
{'host': '146.204.224.152'}
。
See Extract ip addresses from Strings using regex .请参阅使用 regex 从字符串中提取 ip 地址。
Getting both host
and time
from a log line like you have:像您一样从日志行获取
host
和time
:
import re
logdata = r'146.204.224.152 - feest6811 [21/Jun/2019:15:45:24 -0700] "POST /incentivize HTTP/1.1" 302 4622'
match_data = re.search(r'^(?P<host>\S+).*?\[(?P<time>.*?)]', logdata)
if match_data:
print(match_data.groupdict())
See Python proof .参见Python 证明。
EXPLANATION解释
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
(?P<host> group and capture to (?P=host):
--------------------------------------------------------------------------------
\S+ non-whitespace (all but \n, \r, \t, \f,
and " ") (1 or more times (matching the
most amount possible))
--------------------------------------------------------------------------------
) end of (?P=host)
--------------------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
--------------------------------------------------------------------------------
\[ '['
--------------------------------------------------------------------------------
(?P<time> group and capture to (?P=time):
--------------------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
--------------------------------------------------------------------------------
) end of (?P=time)
--------------------------------------------------------------------------------
] ']'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.