String search with character "|"

Asked

Viewed 174 times

2

I need to perform a query in a txt file in Python, but I have 2 problems due to interpretation of special characters.

When I insert | or \ the result is replaced: the | is addressed as white space and \ is duplicated (\\).

import re

erro = r"FIM|2|"
linha = 'ahsuasaudsdad '

if re.search(erro, linha):
   print('Não deveria cair aqui')
   print(re.findall(erro, linha))

In this case I do the string search FIM|2| inside a file, but anyway it returns true in the if and my intention is to return true only if the string contain FIM|2|.

  • 2

    | is an operator of OU, try to change to FIM\|2\|. I mean, this way FIM|2| you are looking for END or 2 or nothing. See the demo

  • That’s right, thank you very much !

  • I had not accepted yet because I can only accept 10 min after he has answered, I would already accept, thank you!

1 answer

5


The problem is that the character | is reserved in regular expression. What is happening is that you are seeking the word "END" or the number "2" or empty. Empty will always be found.

To solve the problem, you need to escape the character:

import re

erro = r"FIM\|2\|"
linha = 'ahsuasaudsdad '

if re.search(erro, linha):
   print('Não deveria cair aqui')
   print(re.findall(erro, linha))
else:
    print('Funcionou :D')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.