Python 使用正则表达式更改url的路径
在Flaski中,一个Python 使用正则表达式更改url的路径,python,regex,flask,Python,Regex,Flask,在Flaski中,一个before\u request函数,它执行一些检查,并在必要时将用户返回到不同的url 我有一个类似于下面的示例的东西,在这里我得到了request\u url,现在我想更改它:https://www.example.com:5000/user/profile/至https://www.example.com:5000/us/user/profile/ @app.before_request def check_location(): country = requ
before\u request
函数,它执行一些检查,并在必要时将用户返回到不同的url
我有一个类似于下面的示例的东西,在这里我得到了request\u url
,现在我想更改它:https://www.example.com:5000/user/profile/
至https://www.example.com:5000/us/user/profile/
@app.before_request
def check_location():
country = request.cookies.get('country')
if country != g.country:
url = request.url
url = re.sub('.com[^\/]*', '.com/us', url)
return redirect(url, 301)
我尝试了一些正则表达式,但在使用带有端口的dev服务器时,这不起作用。所以我的问题是:
url = "https://www.example.com:5000/user/profile/"
url = re.sub('.com[^\/]*', '\g<0>/us', url)
print url # https://www.example.com:5000/us/user/profile/
url=”https://www.example.com:5000/user/profile/"
url=re.sub('.com[^\/]*','\g/us',url)
打印url#https://www.example.com:5000/us/user/profile/
从文档中:
除了如上所述的字符转义和反向引用之外,\g还将使用由(?p…)语法定义的名为name的组匹配的子字符串\g使用相应的组号\因此,g相当于\2,但在替换中(如\g0)并不含糊\20将被解释为对组20的引用,而不是对组2后跟文字字符“0”的引用。反向引用\g替换由RE匹配的整个子字符串
使用组:
url = "https://www.example.com:5000/user/profile/"
url = re.sub('.com[^\/]*', '\g<0>/us', url)
print url # https://www.example.com:5000/us/user/profile/
url=”https://www.example.com:5000/user/profile/"
url=re.sub('.com[^\/]*','\g/us',url)
打印url#https://www.example.com:5000/us/user/profile/
从文档中:
除了如上所述的字符转义和反向引用之外,\g还将使用由(?p…)语法定义的名为name的组匹配的子字符串\g使用相应的组号\因此,g相当于\2,但在替换中(如\g0)并不含糊\20将被解释为对组20的引用,而不是对组2后跟文字字符“0”的引用。反向引用\g替换由RE匹配的整个子字符串
谢谢,从不知道组。谢谢,从不知道组。此请求是来自应用程序内部还是外部?…因为如果是前者,为什么不首先在url中添加语言,而不用使用
re
?@IronFist-outside。如果用户来自我们,并点击了谷歌在英语商店的url,我将需要重定向他们?也许有更好的方法?这个请求是来自应用程序内部还是外部?…因为如果是前者,为什么不首先在url中添加语言,而不用使用re
?@IronFist outside。如果用户来自我们,并点击了谷歌在英语商店的url,我将需要重定向他们?也许有更好的方法?