正则表达式在python中未给出预期结果

2024-09-30 06:29:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个在线编辑器中编写了这个regex,它在那里工作正常,但是每当我将它复制到python时,它就再也找不到我需要的东西了。这是我的密码:

import requests
import re
import os

PAYLOAD = {
    "username": os.environ['USERNAME'],
    "password": os.environ['PASSWORD']
}

LOGIN_URL = "https://ringzer0ctf.com/login"
CHALLENGE_URL = "https://ringzer0ctf.com/challenges/32"

MESSAGE_REG_EX = r"(BEGIN MESSAGE -----<br \/>\n\n\t\t)(\d*)"

with requests.session() as session:
    session.post(LOGIN_URL, data=PAYLOAD)
    r = session.get(CHALLENGE_URL)
    print(r.text)
    num = re.search(MESSAGE_REG_EX, r.text).group(2)
    print(num)

我需要提取开始消息和结束消息之间的第一个数字,在本例中是6907。你知道吗

    <div class="challenge-wrapper">

                <div class="padding_div">

        </div>

        <strong>You have 2 seconds to send the answer</strong><br />

        <strong>Send the answer back using https://ringzer0ctf.com/challenges/32/[answer]</strong>

        <br /><br /><br /><br /><br />

        <div class="message">

        ----- BEGIN MESSAGE -----<br />

        6907 + 0x1d68 - 1010001001100 = ?<br />

        ----- END MESSAGE -----<br />

        </div>

    </div>



<hr />

错误消息:

num = re.search(MESSAGE_REG_EX, r.text).group(2) AttributeError: 'NoneType' object has no attribute 'group'


Tags: texthttpsbrimportdivrecomurl
1条回答
网友
1楼 · 发布于 2024-09-30 06:29:34

也许-或者空格的数量超过了。试试下面的正则表达式

MESSAGE_REG_EX = r"BEGIN MESSAGE -{3,}<br\s*\/>\s*(\d+)" 
match = re.search(MESSAGE_REG_EX, r.text)
if match:
    print (match.group(1))
else:
    print('Failed to find a match :(')

相关问题 更多 >

    热门问题