【问题标题】:Parsing Apache Log using Regex使用正则表达式解析 Apache 日志
【发布时间】:2017-08-23 03:59:28
【问题描述】:

我想得到以下内容:-

输入

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)+[\?]

【问题讨论】:

  • r = re.compile(r'\w+ ([/\w\.]+)')r.match(<string>).groups(1)

标签: python regex python-2.7


【解决方案1】:

以下表达式接受GETPOST

^(?: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']

【讨论】:

    【解决方案2】:

    应该这样做:

    GET\s*(\S*?[\?\s])

    Demo

    这个想法是用非贪婪(又名懒惰)的方法(用*? 表示)搜索?(空格)。 组 1 然后具有所需的捕获文本。

    【讨论】:

      猜你喜欢
      • 2019-07-02
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      • 2019-08-24
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      相关资源
      最近更新 更多