非常簡單的正則運算式,我正在嘗試從日志中提取 IP。但是 group(1) 是空的,這是給定的。有沒有更好的方法來解決這個問題?
sourceip_regex_extract = re.compile(r"{}".format(sourceip_syslog_regex))
sourceip_extract = sourceip_regex_extract.search(message)
sourceip_txt = sourceip_extract.group(1)
Regex101: https://regex101.com/r/jmtQci/1
uj5u.com熱心網友回復:
首先,當您使用正則運算式搜索匹配項時,請確保您確實獲得了匹配項,然后才訪問第一個組值。
接下來,r"{}".format(sourceip_syslog_regex)沒有意義,它與sourceip_syslog_regex.
要解決當前問題,您可以使用(?:from |inside:)交替來匹配from 或inside:
sourceip_syslog_regex = r'(?:from |inside:)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
sourceip_regex_extract = re.compile(sourceip_syslog_regex)
sourceip_extract = sourceip_regex_extract.search(message)
if sourceip_extract:
sourceip_txt = sourceip_extract.group(1)
請參閱正則運算式演示
請注意,您可以稍微縮短 IP 地址匹配模式并使用(?:from |inside:)(\d{1,3}(?:\.\d{1,3}){3}).
詳情:
(?:from |inside:)-from要么inside:(\d{1,3}(?:\.\d{1,3}){3})- 第 1 組:一到三個數字,然后出現三個 a.和一到三個數字。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/535567.html
標籤:Python正则表达式
