Apo*_*llo 5 python regex string syntax
我从Regex 的文档中找到了以下正则表达式替换示例.r关于字符串之前的前缀是什么,我有点困惑?
re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
... r'static PyObject*\npy_\1(void)\n{',
... 'def myfunc():')
Run Code Online (Sandbox Code Playgroud)
iCo*_*dez 15
放置在字符串文字之前r或R之前会创建所谓的原始字符串文字.原始字符串不处理转义序列(\n,\b等),并因此通常用于正则表达式模式,这往往含有大量的\字符.
以下是演示:
>>> 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
>>>
Run Code Online (Sandbox Code Playgroud)
唯一的另一种选择是加倍每个反斜杠:
re.sub('def\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*\\(\\s*\\):',
... 'static PyObject*\\npy_\\1(void)\\n{',
... 'def myfunc():')
Run Code Online (Sandbox Code Playgroud)
这很乏味.
| 归档时间: |
|
| 查看次数: |
3047 次 |
| 最近记录: |