开发者

Confused about a simple regex with sub

开发者 https://www.devze.com 2023-02-12 23:13 出处:网络
I have following python code: TRAC_REQUEST_LOCATION=\"\" TRAC_ENV=TRAC_ENV_PARENT+\"/\"+re.sub(r\'^\'+TRAC_REQUEST_LOCATION+\'/([^/]+).*\', r\'\\1\', environ[\'REQUEST_URI\'])

I have following python code:

TRAC_REQUEST_LOCATION=""    

TRAC_ENV=TRAC_ENV_PARENT+"/"+re.sub(r'^'+TRAC_REQUEST_LOCATION+'/([^/]+).*', r'\1', environ['REQUEST_URI'])

The content of environ['REQUEST_URI'] is something like that /abc/DEF and I want to get only abc, but it doesn't work. Only sometimes it works, but why?

Thanks for any advices.

EDIT:

Here is the new code consisting on the given answers:

def check_password(environ, user, password):
    global acct_mgr, TRAC_ENV

    TRAC_ENV = ''

    if 'REQUEST_URI' in environ:
        if '/' in environ['REQUEST_URI']:
             TRAC_ENV = environ['REQUEST_URI'].split('/')[1]
    else:
        return None

开发者_StackOverflow社区But I get as TRAC_ENV things like /abc/ or /abc, but I need only the abc part.

What is wrong with the code?


Why do you need a regexp? Use urlparse (Python 2.x, there is a link for Python 3.x in there).


If you want to extract the first part of the request path this is the simplest solution:

TRAC_ENV = ''
if '/' in environ['REQUEST_URI']:
    TRAC_ENV = environ['REQUEST_URI'].split('/')[1]

EDIT

An example usage:

>>> def trac_env(environ):
...     trac_env = ''
...     if '/' in environ['REQUEST_URI']:
...         trac_env = environ['REQUEST_URI'].split('/')[1]
...     return trac_env
... 
>>> trac_env({'REQUEST_URI': ''})
''
>>> trac_env({'REQUEST_URI': '/'})
''
>>> trac_env({'REQUEST_URI': '/foo'})
'foo'
>>> trac_env({'REQUEST_URI': '/foo/'})
'foo'
>>> trac_env({'REQUEST_URI': '/foo/bar'})
'foo'
>>> trac_env({'REQUEST_URI': '/foo/bar/'})
'foo'


I am back to my code above and it works fine now.
Perhaps the update of the components was the solution.

0

精彩评论

暂无评论...
验证码 换一张
取 消