Skip to main content
 首页 » 编程设计

python之使用正则表达式解析 Apache 日志

2025年02月15日28sky-heaven

我想得到以下内容:-

输入

GET /1.1/friendships/list.json?user_id=123 HTTP/1.1 
GET /1.1/friendships/list.json HTTP/1.1 
GET /1.1/users/show.json?include_entities=1&user_id=321 HTTP/1.1 
GET /1.1/friendships/list.json?user_id=234 HTTP/1.1 
GET /1.1/friendships/create.json HTTP/1.1 

输出

/1.1/friendships/list.json 
/1.1/friendships/list.json 
/1.1/users/show.json 
/1.1/friendships/list.json 
/1.1/friendships/create.json 

我一直能够匹配到问号字符。我想匹配一个问号或空格的字符。这是我目前所拥有的。

([A-Z])+ (\S)+[\?] 

请您参考如下方法:

以下表达式接受GET 和POST:

^(?:GET|POST)\s+([^?\n\r]+).*$ 

分解,这说

^               # start of line 
(?:GET|POST)\s+ # GET or POST literally, at least one whitespace 
([^?\s]+)       # not a question mark nor whitespace characters 
.*              # 0+ chars afterwards 
$               # end of line 

这需要替换为\1,参见a demo on regex101.com并注意 MULTILINE 标志。


在 Python 中,这将是:

import re 
 
string = """ 
GET /1.1/friendships/list.json?user_id=123 HTTP/1.1 
GET /1.1/friendships/list.json HTTP/1.1 
GET /1.1/users/show.json?include_entities=1&user_id=321 HTTP/1.1 
GET /1.1/friendships/list.json?user_id=234 HTTP/1.1 
GET /1.1/friendships/create.json HTTP/1.1 
POST /some/other/url/here 
""" 
 
rx = re.compile(r'^(?:GET|POST)\s+([^?\s]+).*$', re.M) 
matches = rx.findall(string) 
print(matches) 
# ['/1.1/friendships/list.json', '/1.1/friendships/list.json', '/1.1/users/show.json', '/1.1/friendships/list.json', '/1.1/friendships/create.json', '/some/other/url/here']