Python Regex escape operator \ in substitutions & raw strings

前端 未结 2 549
既然无缘
既然无缘 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, \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'\.\.

提交回复
热议问题