简体   繁体   中英

Regex to match space and a string until a forward slash

I have two django urls,

(r'^groups/(?P<group>[\w|\W\-\.]{1,60})$')
(r'^groups/(?P<group>[\w|\W\-\.]{1,60})/users$'

The regex ([\\w|\\W\\-\\.])$ in the urls matches soccer players and soccer players/users . Can someone help get a regex that matches anything between groups and / . I want the regex to match anything after the groups until it encounters a /

You simply need to do the following, which will match anything up to a slash:-

regexp = re.compile(r'^group/(?P<group>[^/]+)$')

For the case where you need to match urls like your example with a trailing /user , you simply add this to the expression:-

regexp = re.compile(r'^group/(?P<group>[^/]+)/users$')

If you needed to get a user id, for example, you could also use the same matching:-

regexp = re.compile(r'^group/(?P<group>[^/]+)/users/(?P<user>[^/]+)$')

Then you can get the result:-

match = regexp.match(url) # "group/soccer players/users/123"
if match:
    group = match.group("group") # "soccer players"
    user = match.group("user") # "123"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM