sre_constants.error

来源:3-4 正则表达式-3

autista

2017-09-13

line = '她出生于2001-06'
reg_str = '.*(\d{4}[年-/]\d{1,2})'
match_obj = re.match(reg_str, line)
if match_obj:
    print(match_obj.group(1))

python环境是3.6.2,我尝试匹配“2001-06”,用pycharm运行报错:sre_constants.error: bad character range 年-/ at position 9


写回答

1回答

autista

提问者

2017-09-13

看了下bobby老师在其他疑问的回答, 原因是"-"在中括号中需要转义,代码对应改成“[年\-/]”这样就行了,对了下教程,老师写的是[年/-],将“-”放在最后,这样就不报错,这样是可以省略转义符,还是什么其他原因?

1
2
慕用7288366
https://www.cnblogs.com/wxshi/p/6827056.html 这里有解答。
2018-03-14
共2条回复

Scrapy打造搜索引擎 畅销4年的Python分布式爬虫课

带你彻底掌握Scrapy,用Django+Elasticsearch搭建搜索引擎

5813 学习 · 6291 问题

查看课程