python 使用 re 模块报错 re.error: unknown extension ?<n at position

博客主要围绕Python开发中出现的正则表达式异常展开。介绍了异常格式为re.error: unknown extension?<n at position 一个位置数字,属于正则表达式中位置模板内容。同时给出解决方案,即在re模块分组命名时写对符号,并展示了修改代码。还提供错误提示样板及爬虫100例课程宣传。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

异常解读

该异常的格式一般为:

re.error: unknown extension ?<n at position 一个位置数字

本异常看文字提示能大概猜出 BUG 问题所在,属于正则表达式中位置模板内容。出现的位置是 <?,例如下述代码就会报错。

import re
pattern = re.compile(r'a(?<code>\d+)')
match = pattern.search("a123456")
print(match)

异常解决方案

修改办法比较容易,是因为在 re 模块中进行分组命名时,符号写对即可,具体格式为 ?P<名称>
修改代码如下:

import re
pattern = re.compile(r'a(?P<code>\d+)')
match = pattern.search("a123456")
print(match.group('code'))

附录

本系列文章只供记录 Python 日常开发过程中 偶遇 BUG,提供给学生作为参考数据与解决方案用,属于记录型博客,有缘分看到的读者希望可解决你的问题。

错误提示样板,可以与你的错误进行比对。

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner
    self.run()
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "e:/crawl100/xiaoke1/mingxing.py", line 57, in get_list
    get_detail(detail_url)
  File "e:/crawl100/xiaoke1/mingxing.py", line 18, in get_detail
    r'<h1>(?<name>.*?)<span>(?P<type>.*?)</span></h1>', html)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\re.py", line 183, in search
    return _compile(pattern, flags).search(string)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\re.py", line 286, in _compile
    p = sre_compile.compile(pattern, flags)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\sre_compile.py", line 764, in compile
    p = sre_parse.parse(p, flags)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\sre_parse.py", line 930, in parse
    p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\sre_parse.py", line 426, in _parse_sub
    not nested and not items))
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\sre_parse.py", line 731, in _parse
    len(char) + 2)
re.error: unknown extension ?<n at position 5

爬虫 100 例课程宣传

python 使用 re 模块报错 re.error: unknown extension ?<n at position
爬虫百例教程导航链接 : https://blog.youkuaiyun.com/hihell/article/details/86106916

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦想橡皮擦

如有帮助,来瓶可乐

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值