Python 中的正则表达式反向引用问题 [英] Issue with regex backreference in Python

查看:54
本文介绍了Python 中的正则表达式反向引用问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定为什么这不起作用.也许我在 Python 正则表达式中遗漏了一些东西.

I am not sure why this is not working. Perhaps I am missing something with Python regex.

这是我的正则表达式和我希望它匹配的示例字符串:

Here is my regex and an example string of what I want it to match too:

    PHONE_REGEX        = "<(.*)>phone</\1>"
    EXAMPLE            = "<bar>phone</bar>"

我单独测试了这场比赛,但失败了.我使用了一个在线正则表达式测试器,它匹配.我是否只是遗漏了 Python 正则表达式特有的东西?

I tested this match in isolation and it failed. I used an online regex tester and it matched. Am I simply missing something that is particular to Python regex?

谢谢!

推荐答案

你必须将字符串标记为原始字符串,因为 \ 在那里,通过放置一个 r 在正则表达式前:

You have to mark the string as a raw string, due to the \ in there, by putting an r in front of the regex:

m = re.match(r"<(.*)>phone</\1>", "<bar>phone</bar>")

这篇关于Python 中的正则表达式反向引用问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆