我有一个正则表达式,可以去掉请求URL的结尾:
re.sub('(?:^\/en\/category).*(-\d{1,4}$)', '', r)
我的问题是文档说它会替换匹配的部分,但当它匹配我的字符串时,它替换了整个字符串,例如:
/en/category/specials/men-2610
我不确定Python在做什么,但是我的正则表达式似乎没问题。 < p>编辑:我希望将字符串的结尾去掉,目标=
/en/category/specials/men
我有一个正则表达式,可以去掉请求URL的结尾:
re.sub('(?:^\/en\/category).*(-\d{1,4}$)', '', r)
我的问题是文档说它会替换匹配的部分,但当它匹配我的字符串时,它替换了整个字符串,例如:
/en/category/specials/men-2610
/en/category/specials/men
(^/en/category.*)-\d{1,4}$
使用反向引用 \1
将其放回字符串中:
re.sub(r'(^/en/category.*)-\d{1,4}$', r'\1', text)
(?<=^\/en\/category)(.*)-\d{1,4}$
\1
替换this.replace
。请查看演示。https://regex101.com/r/tX2bH4/27。您的整个模式匹配,因此它替换了整个字符串。P.S. match
与captures或groups
不同。import re
p = re.compile(r'(?<=^\/en\/category)(.*)-\d{1,4}$', re.IGNORECASE)
test_str = "/en/category/specials/men-2610"
subst = "\1"
result = re.sub(p, subst, test_str)
\1
替换匹配项,如果模式定义为原始字符串,则不需要转义正斜杠。re.sub(r'^(/en/category.*)-\d{1,4}$', r'\1', string)
可以翻译为:{{链接1:演示}}
。>>> s = "/en/category/specials/men-2610"
>>> re.sub(r'^(/en/category.*)-\d{1,4}$', r'\1', s)
'/en/category/specials/men'
或者
>>> s.split('-')[0]
'/en/category/specials/men'
>>> re.sub('(^\/en\/category.*)(-\d{1,4}$)',
r'\1', '/en/category/specials/men-2610')
'/en/category/specials/men'
之前:
(?:^\/en\/category).*(-\d{1,4}$)
之后:
((?:^\\/en\\/category).*)-\\d{1,4}$
由于不再需要使用?:
,我们可以进一步简化代码:
(^\\/en\\/category.*)-\\d{1,4}$
注意,我已将捕获组从数字移到其前面的部分。
示例: