0

Suppose I have the following code (taken from Google's Python Class) which assists with pattern matching by checking if a piece of regex lies within a text

def Find(pat, text):
    match=re.search(pat,text)
    if match: print (match.group())
    else: print('not found')

When I run Find(r'\n', '\\n'), the function returns not found.

From my understanding, the r in r'\n' removes the special meaning from the newline character, meaning that r'\n' and '\\n' are essentially identical strings. Why then, does the above function return not found?

gcv
  • 1
  • Funny enough `Find(r'\n', '\n')` is found – Alexey S. Larionov Sep 04 '21 at 09:24
  • Does this answer your question? [How to match a new line character in Python raw string](https://stackoverflow.com/questions/14689531/how-to-match-a-new-line-character-in-python-raw-string) – chiefenne Sep 04 '21 at 09:25
  • The regular expression `\n` still matches a literal newline, not a literal backslash and a literal `n`. You need two backslashes in the expression which reaches the regex engine, so `r'\\n'` or `'\\\\n'` (sic) – tripleee Sep 04 '21 at 10:32

0 Answers0