Skip to main content
 首页 » 编程设计

python之使用 re.match 提取 url 模式中的部分

2025年05月04日30shangdawei

在 nodejs 中,我使用正则表达式提取此 url 中 tenant 下的子部分,http://myServer:8000/api/running/tenant/sk/services。它打印正确,sk。

代码是,

var re = /(?:[\w\W]+)\/tenant\/([\w]+?)\/(?:[\w\W]*)/ 
var results = re.exec('http://myServer:8000/api/running/tenant/sk/services') 
console.log(results[1]) 

我将代码移到了 python 中,

import re 
m = re.match(r"(?:\w\W+)tenant/(\w+)/(?:[\w\W]*)", "http://myServer:8000/api/running/tenant/sk/services") 
m.group(1) 

它抛出 AttributeError: 'NoneType' object has no attribute 'group'

为什么它不匹配 tenant 之后的一个词?

请您参考如下方法:

findall/search 应该能帮到你

寻找

>>> m = re.findall(r"(?:\w\W+)tenant/(\w+)/(?:[\w\W]*)", "http://myServer:8000/api/running/tenant/sk/services") 
>>> m 
['sk'] 

搜索

>>> m = re.search(r"(?:\w\W+)tenant/(\w+)/(?:[\w\W]*)", "http://myServer:8000/api/running/tenant/sk/services") 
>>> m.group(1) 
'sk' 

匹配失败的原因是因为它试图在字符串的开头匹配它 re.match documentation

re.match(pattern, string, flags=0) If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match.

Note that even in MULTILINE mode, re.match() will only match at the beginning of the string and not at the beginning of each line.

If you want to locate a match anywhere in string, use search() instead (see also search() vs. match()).