Python Regex escape operator \ in substitutions & raw strings

前端 未结 2 533
既然无缘
既然无缘 2020-11-29 12:03

I don\'t understand the logic in the functioning of the scape operator \\ in python regex together with r\' of raw strings. Some help is appreciated.

code:



        
相关标签:
2条回答
  • 2020-11-29 12:55

    From the doc (my emphasis):

    re.sub(pattern, repl, string, count=0, flags=0) Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \& are left alone. Backreferences, such as \6, are replaced with the substring matched by group 6 in the pattern.

    The repl argument is not just plain text. It can also be the name of a function or refer to a position in a group (e.g. \g<quote>, \g<1>, \1).

    Also, from here:

    Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the result.

    Since . is not a special escape character, '\.' is the same as r'\.\.

    0 讨论(0)
  • 2020-11-29 13:01

    First and foremost,

    replacement patterns ≠ regular expression patterns
    

    We use a regex pattern to search for matches, we use replacement patterns to replace matches found with regex.

    Replacement pattern syntax in Python

    The re.sub docs are confusing as they mention both string escape sequences that can be used in replacement patterns (like \n, \r) and regex escape sequences (\6) and those that can be used as both regex and string escape sequences (\&).

    I am using the term regex escape sequence to denote an escape sequence consisting of a literal backslash + a character, that is, '\\X' or r'\X', and a string escape sequence to denote a sequence of \ and a char or some sequence that together form a valid string escape sequence. They are only recognized in regular string literals. In raw string literals, you can only escape " (and that is the reason why you can't end a raw string literal with \", but the backlash is still part of the string then).

    So, in a replacement pattern, you may use backreferences:

    re.sub(r'\D(\d)\D', r'\1', 'a1b')    # => 1
    re.sub(r'\D(\d)\D', '\\1', 'a1b')    # => 1
    re.sub(r'\D(\d)\D', '\g<1>', 'a1b')  # => 1
    re.sub(r'\D(\d)\D', r'\g<1>', 'a1b') # => 1
    

    You may see that r'\1' and '\\1' is the same replacement pattern, \1. If you use '\1', it will get parse as a string escape sequence, a character with octal value 001. If you forget to use r prefix with the unambiguous backreference, there is no problem because \g is not a valid string escape sequence, and there, \ escape character remains in the string. Read on the docs I linked to:

    Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the result.

    So, when you pass '\.' as a replacement string, you actually send \. two-char combination as the replacement string, and that is why you get \. in the result.

    \ is a special character in Python replacement pattern

    If you use re.sub(r'\s+\.', r'\\.', text), you will get the same result as in text2 and text3 cases, see this demo.

    That happens because \\, two literal backslashes, denote a single backslash in the replacement pattern. If you have no Group 2 in your regex pattern, but pass r'\2' in the replacement to actually replace with \ and 2 char combination, you would get an error.

    Thus, when you have dynamic, user-defined replacement patterns you need to double all backslashes in the replacement patterns that are meant to be passed as literal strings:

    re.sub(some_regex, some_replacement.replace('\\', '\\\\'), input_string)
    
    0 讨论(0)
提交回复
热议问题