正则表达式模式前的“r"是什么意思? [英] What does 'r' mean before a Regex pattern?

查看:100
本文介绍了正则表达式模式前的“r"是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从正则表达式的文档中找到了以下正则表达式替换示例.我对前缀 r 在字符串之前的作用有点困惑?

re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',... r'静态 PyObject*\npy_\1(void)\n{',... 'def myfunc():')

解决方案

在字符串字面量之前放置 rR 创建所谓的 raw-string 文字.原始字符串不处理转义序列(\n\b 等),因此常用于 Regex 模式,这些模式通常包含很多 \ 字符.

以下是演示:

<预><代码>>>>print('\n') # 打印换行符>>>print(r'\n') # 不处理转义序列\n>>>print('\b') # 打印退格字符>>>print(r'\b') # 不处理转义序列\b>>>

唯一的其他选择是将每个反斜杠加倍:

re.sub('def\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*\\(\\s*\\):',... '静态 PyObject*\\npy_\\1(void)\\n{',... 'def myfunc():')

这很乏味.

I found the following regex substitution example from the documentation for Regex. I'm a little bit confused as to what the prefix r does before the string?

re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
 ...        r'static PyObject*\npy_\1(void)\n{',
 ...        'def myfunc():')

解决方案

Placing r or R before a string literal creates what is known as a raw-string literal. Raw strings do not process escape sequences (\n, \b, etc.) and are thus commonly used for Regex patterns, which often contain a lot of \ characters.

Below is a demonstration:

>>> print('\n') # Prints a newline character


>>> print(r'\n') # Escape sequence is not processed
\n
>>> print('\b') # Prints a backspace character

>>> print(r'\b') # Escape sequence is not processed
\b
>>>

The only other option would be to double every backslash:

re.sub('def\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*\\(\\s*\\):',
 ...        'static PyObject*\\npy_\\1(void)\\n{',
 ...        'def myfunc():')

which is just tedious.

这篇关于正则表达式模式前的“r"是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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