正则表达式匹配空格和字符串直到正斜杠

时间:2021-05-23 23:41:03

I have two django urls,

我有两个django网址,

(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 /

网址中的正则表达式([\ w | \ W \ - \。])$匹配足球运动员和足球运动员/用户。有人可以帮助获得匹配组和/之间任何内容的正则表达式。我希望正则表达式匹配组之后的任何内容,直到遇到/

1 个解决方案

#1


6  

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:-

对于需要将示例中的url与尾随/用户匹配的情况,只需将其添加到表达式: -

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:-

例如,如果您需要获取用户ID,您也可以使用相同的匹配: -

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"

#1


6  

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:-

对于需要将示例中的url与尾随/用户匹配的情况,只需将其添加到表达式: -

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:-

例如,如果您需要获取用户ID,您也可以使用相同的匹配: -

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"