正则表达式匹配基于前缀和后缀

时间:2015-08-18 13:47:18

标签: python regex

我正在使用python 3和re模块。

以下是字符串:

s1 = "http://52portal/flood-2011-year-39090/gallery?p=3"
s2 = "http://52portal/flood-2011-year-39090"

我需要获得39090个数字,总是给出ID,以便该数字具有前缀-且没有特定的后缀。

当url中没有其他数字时,我有一个实现:

pattern = r'-([0-9]+)'
re.findall(pattern, s)[0]

我如何告诉程序忽略带后缀和前缀-的数字?

2 个答案:

答案 0 :(得分:3)

您需要找到右侧边界。它可以是/或字符串结尾。

(?<=-)\d+(?=/|$)

在这里,(?<=-)是一个积极的外观,可以检查在一个或多个数字(\d+)之前是否有连字符,而(?=/|$)是一个肯定的前瞻,以确保在该序列之后有/或字符串结尾。

请参阅demo

以下是sample code

import re
p = re.compile(r'(?<=-)\d+(?=/|$)')
test_str = "http://52portal/flood-2011-year-39090/gallery?p=3\nhttp://52portal/flood-2011-year-39090"
print(re.findall(p, test_str))

答案 1 :(得分:1)

尝试

(?<=-)[0-9]+?(?=/|$)

https://regex101.com/r/sY3qI2/2

相关问题