V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
RangerWolf
V2EX  ›  Python

一个正则表达式, Python 的 re.compile 之后,丢失部分信息,搞不懂,特来求助

  •  
  •   RangerWolf · 27 天前 · 1182 次点击
    
    # 注意这个 pattern 的最后一部分是 req_id
    pattern = r'(?P<remote_addr>.*?)\ \-\ (?P<remote_user>.*?)\ \[(?P<time_local>.*?)\]\ "(?P<request>.*?)"\ (?P<status>.*?)\ (?P<body_bytes_sent>.*?)\ "(?P<http_referer>.*?)"\ "(?P<http_user_agent>.*?)"\ (?P<req_id>.*?)'
    
    regex = re.compile(pattern)
    print("---- regex:", regex)
    

    print 出来的结果:

    ---- regex: re.compile('(?P<remote_addr>.?)\ \-\ (?P<remote_user>.?)\ \[(?P<time_local>.?)\]\ "(?P<request>.?)"\ (?P<status>.?)\ (?P<body_bytes_sent>.?)\ "(?P<http_referer>.?)"\ "(?P<http_user_agent>.?)")

    缺少了最后一部分req_id,到了http_user_agent就结束了。。。
    一直想不通为什么,特来求助

    第 1 条附言  ·  27 天前
    大家可以试试看下面这个测试的字符串:
    ```python
    test_string = '192.168.1.1 - john [10/Oct/2000:13:55:36 -0700] "GET /index.html" 200 1234 "http://example.com" "Mozilla/5.0" 123123'
    ```

    看看能不能把 request_id 123123 解析出来
    第 2 条附言  ·  27 天前
    有大神解决了。。。pattern 后面加一个$
    5 条回复    2024-08-20 11:26:04 +08:00
    ladypxy
        1
    ladypxy  
       27 天前
    扔到 regex101 里看一眼就好了。
    双引号前要加\
    zk8802
        2
    zk8802  
       27 天前   ❤️ 1
    这个应该是 pattern.__repr__() 显示的问题。你可以试试 print(regex.pattern),结果应该是正确的。
    lzoje
        3
    lzoje  
       27 天前
    问 chatgpt 说只是 print 输出显示问题,你 print regex.pattern 就是完整的了
    FlyaiF
        4
    FlyaiF  
       27 天前
    试了下最后一个捕获组 req_id 不能用贪婪匹配,匹配到空了。
    正则应该是完整的,应该是 print 问题。
    NoOneNoBody
        5
    NoOneNoBody  
       27 天前
    长字符串最好用三引号
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1000 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 19:17 · PVG 03:17 · LAX 12:17 · JFK 15:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.