Python 正则表达式替换整个字符串
Python regex replace whole string
我有一个正则表达式来去除请求的结尾 url:
re.sub('(?:^\/en\/category).*(-\d{1,4}$)', '', r)
我的问题是文档说它将替换匹配的部分,但是当它与我的字符串匹配时它会替换 整个字符串,例如:
/en/category/specials/men-2610
我不确定 Python 在做什么,但是 my regex seems fine
编辑:我希望字符串的结尾被剥离,target =
/en/category/specials/men
(?<=^\/en\/category)(.*)-\d{1,4}$
通过 </code> 尝试 this.replace。查看演示。</p>
<p><a href="https://regex101.com/r/tX2bH4/27" rel="nofollow">https://regex101.com/r/tX2bH4/27</a></p>
<p>您的整个模式匹配,这就是它替换整个字符串的原因。</p>
<p>P.S <code>match
不同于 captures or groups
。
import re
p = re.compile(r'(?<=^\/en\/category)(.*)-\d{1,4}$', re.IGNORECASE)
test_str = "/en/category/specials/men-2610"
subst = ""
result = re.sub(p, subst, test_str)
只需将捕获组转移到其他部分,然后用</code>替换匹配,如果模式定义为原始字符串,则不需要转义正斜杠。</p>
<pre><code>re.sub(r'^(/en/category.*)-\d{1,4}$', r'', string)
>>> s = "/en/category/specials/men-2610"
>>> re.sub(r'^(/en/category.*)-\d{1,4}$', r'', s)
'/en/category/specials/men'
或
>>> s.split('-')[0]
'/en/category/specials/men'
>>> re.sub('(^\/en\/category.*)(-\d{1,4}$)',
r'', '/en/category/specials/men-2610')
'/en/category/specials/men'
如文档中所述,匹配部分 已被替换。 匹配不同于捕获。
您必须像这样在捕获组中捕获您不想删除的文本:
(^/en/category.*)-\d{1,4}$
并使用反向引用将其放回字符串中 </code>:</p>
<pre><code>re.sub(r'(^/en/category.*)-\d{1,4}$', r'', text)
你的模式没问题,你只需要改变哪个项目是捕获组:
之前:
(?:^\/en\/category).*(-\d{1,4}$)
之后:
((?:^\/en\/category).*)-\d{1,4}$
由于不再需要 ?:
,我们可以将其进一步缩减为:
(^\/en\/category.*)-\d{1,4}$
请注意,我已将捕获组从数字移到它之前的部分。
示例:
我有一个正则表达式来去除请求的结尾 url:
re.sub('(?:^\/en\/category).*(-\d{1,4}$)', '', r)
我的问题是文档说它将替换匹配的部分,但是当它与我的字符串匹配时它会替换 整个字符串,例如:
/en/category/specials/men-2610
我不确定 Python 在做什么,但是 my regex seems fine
编辑:我希望字符串的结尾被剥离,target =
/en/category/specials/men
(?<=^\/en\/category)(.*)-\d{1,4}$
通过 </code> 尝试 this.replace。查看演示。</p>
<p><a href="https://regex101.com/r/tX2bH4/27" rel="nofollow">https://regex101.com/r/tX2bH4/27</a></p>
<p>您的整个模式匹配,这就是它替换整个字符串的原因。</p>
<p>P.S <code>match
不同于 captures or groups
。
import re
p = re.compile(r'(?<=^\/en\/category)(.*)-\d{1,4}$', re.IGNORECASE)
test_str = "/en/category/specials/men-2610"
subst = ""
result = re.sub(p, subst, test_str)
只需将捕获组转移到其他部分,然后用</code>替换匹配,如果模式定义为原始字符串,则不需要转义正斜杠。</p>
<pre><code>re.sub(r'^(/en/category.*)-\d{1,4}$', r'', string)
>>> s = "/en/category/specials/men-2610"
>>> re.sub(r'^(/en/category.*)-\d{1,4}$', r'', s)
'/en/category/specials/men'
或
>>> s.split('-')[0]
'/en/category/specials/men'
>>> re.sub('(^\/en\/category.*)(-\d{1,4}$)',
r'', '/en/category/specials/men-2610')
'/en/category/specials/men'
如文档中所述,匹配部分 已被替换。 匹配不同于捕获。
您必须像这样在捕获组中捕获您不想删除的文本:
(^/en/category.*)-\d{1,4}$
并使用反向引用将其放回字符串中 </code>:</p>
<pre><code>re.sub(r'(^/en/category.*)-\d{1,4}$', r'', text)
你的模式没问题,你只需要改变哪个项目是捕获组:
之前:
(?:^\/en\/category).*(-\d{1,4}$)
之后:
((?:^\/en\/category).*)-\d{1,4}$
由于不再需要 ?:
,我们可以将其进一步缩减为:
(^\/en\/category.*)-\d{1,4}$
请注意,我已将捕获组从数字移到它之前的部分。
示例: