python - What does 'r' mean before a Regex pattern? -
i found next regex substitution illustration documentation regex. i'm little bit confused prefix r
before 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 string literal creates known raw-string literal. raw strings not process escape sequences (\n
, \b
, etc.) , commonly used regex patterns, contain lot of \
characters.
below demonstration:
>>> print('\n') # prints newline character >>> print(r'\n') # escape sequence not processed \n >>> print('\b') # prints backspace character >>> print(r'\b') # escape sequence not processed \b >>>
the other alternative 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 tedious.
python regex string syntax
No comments:
Post a Comment