如何在python中使用'\Q'和'\E'正则表达式符号? [英] How to use '\Q' and '\E' regex symbols in python?

查看:244
本文介绍了如何在python中使用'\Q'和'\E'正则表达式符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这应该是有效的,但是它不是:

  import re 
如果re.match \Qbla\E,bla):
printworks!

为什么它不起作用?我可以在python中使用'\Q'和'\E'符号吗?如何?

解决方案

Python的正则表达式引擎不支持那些;请参阅§ 7.2.1 Python文档中的正则表达式语法支持 的列表。但是,您可以通过编写 re.match(re.escape(bla),bla)获得相同的效果; re.escape 是一个在所有特殊字符之前插入反斜杠的功能。



顺便说一句,你一般应该使用原始字符串, r...而不是...,否则反斜杠将被处理两次(一旦解析了字符串,然后再由正则表达式引擎),这意味着你必须写出如 \\b 而不是 \b 。使用 r...防止第一次处理通过,所以你可以写 \b 。 p>

I thought this should work, but it doesn't:

import re
if re.match("\Qbla\E", "bla"):
    print "works!"

Why it doesn't work? Can I use the '\Q' and '\E' symbols in python? How?

解决方案

Python's regex engine doesn't support those; see §7.2.1 "Regular Expression Syntax" in the Python documentation for a list of what it does support. However, you can get the same effect by writing re.match(re.escape("bla"), "bla"); re.escape is a function that inserts backslashes before all special characters.

By the way, you should generally use "raw" strings, r"..." instead of just "...", since otherwise backslashes will get processed twice (once when the string is parsed, and then again by the regex engine), which means you have to write things like \\b instead of \b. Using r"..." prevents that first processing pass, so you can just write \b.

这篇关于如何在python中使用'\Q'和'\E'正则表达式符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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