求匹配下划线与斜杠间1-9999非全零数字的正则表达式
正则表达式提取指定位置数字方案
需求说明
从给定URL中提取位于下划线_与斜杠/之间的数字,要求数字范围为1-9999,且排除全为0的数字(如_0000/这类情况不匹配)。
正则表达式
(?<=_)(?!0+$)([1-9]\d{0,3})(?=/)
表达式拆解
(?<=_):正向零宽断言,确保目标数字前紧邻下划线_(?!0+$):负向零宽断言,排除全部由0组成的数字序列([1-9]\d{0,3}):匹配1-9999的有效数字:第一位为1-9的非零数字,后续可跟0-3位任意数字(?=/):正向零宽断言,确保目标数字后紧邻斜杠/
测试结果
针对提供的URL列表,提取出的数字列表为:
- 999
- 998
- 995
- 991
- 984
- 983
示例代码(Python)
import re url_list = [ "catalogue/tipping-the-velvet_999/index.html", "catalogue/soumission_998/index.html", "catalogue/the-requiem-red_995/index.html", "catalogue/the-black-maria-1700-1749_991/index.html", "catalogue/olio_984/index.html", "catalogue/mesaerion-the-best-science-fiction-stories-1800-1849_983/index.html" ] regex_pattern = r'(?<=_)(?!0+$)([1-9]\d{0,3})(?=/)' extracted_numbers = [re.search(regex_pattern, url).group(1) for url in url_list if re.search(regex_pattern, url)] print(extracted_numbers)
运行后输出:['999', '998', '995', '991', '984', '983']
内容的提问来源于stack exchange,提问作者spyhabs
相关产品推荐
相关产品推荐

