带问号文字的Python正则表达式 [英] Python regex with question mark literal

查看:179
本文介绍了带问号文字的Python正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django的URLconf,我将收到的URL是 /?code = authenticationcode


我想匹配使用 r'^ \?code =(?P 。*)$'的URL,但这无效。

I'm using Django's URLconf, the URL I will receive is /?code=authenticationcode
I want to match the URL using r'^\?code=(?P<code>.*)$' , but it doesn't work.

然后我发现这是‘?’问题。


因为我试图使用 r'aaa\?aaa'匹配 / aaa?aaa code> r'aaa\\?aaa'甚至 r'aaa。* aaa',都失败了,但是当它是 +或任何其他字符时,它可以工作。


如何匹配'?',是否特别?

Then I found out it is the problem of '?'.
Becuase I tried to match /aaa?aaa using r'aaa\?aaa' r'aaa\\?aaa' even r'aaa.*aaa' , all failed, but it works when it's "+" or any other character.
How to match the '?', is it special?

推荐答案

>>> s="aaa?aaa"
>>> import re
>>> re.findall(r'aaa\?aaa', s)
['aaa?aaa']

/ aaa?aaa 在您的URL中不匹配的原因是因为以新的GET查询。

The reason /aaa?aaa won't match inside your URL is because a ? begins a new GET query.

因此,URL的可匹配部分仅取决于第一个 aaa。其余的?aaa是一个新的查询字符串,以?号分隔,其中包含一个变量 aaa作为GET参数传递。

So, the matchable part of the URL is only up to the first 'aaa'. The remaining '?aaa' is a new query string separated by the '?' mark, containing a variable "aaa" being passed as a GET parameter.

您在这里 所能做的就是在变量进入URL之前对其进行编码。 的编码形式为%3F

What you can do here is encode the variable before it makes its way into the URL. The encoded form of ? is %3F.

您也不应该完全使用正则表达式来匹配GET查询,例如 /?code = authenticationcode 。而是使用 r’^ $’将您的URL匹配到 / 。 Django会将变量 code 作为GET参数传递给 request 对象,您可以在视图中使用 request.GET.get('code')

You should also not match a GET query such as /?code=authenticationcode using regex at all. Instead, match your URL up to / using r'^$'. Django will pass the variable code as a GET parameter to the request object, which you can obtain in your view using request.GET.get('code').

这篇关于带问号文字的Python正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆