Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用正则表达式更改url的路径_Python_Regex_Flask - Fatal编程技术网

Python 使用正则表达式更改url的路径

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

在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 = request.cookies.get('country')
    if country != g.country:
        url = request.url
        url = re.sub('.com[^\/]*', '.com/us', url)
        return redirect(url, 301)
我尝试了一些正则表达式,但在使用带有端口的dev服务器时,这不起作用。所以我的问题是:

  • 我如何编写这个正则表达式以获得更好的匹配
  • 用正则表达式做这个可以吗?还是Flask有更好的方法
  • 使用组:

    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,我将需要重定向他们?也许有更好的方法?