Need help with a regular expression, or rather with the preparation of the template, to search for a full match with the string.

Example:

import re word = input() with open('first.txt', 'r') as file1: line = file1.read() if re.search(word, line): #т.к.ищется первое вхождение, то нужно как - то настроить шаблон, и я не понимаю как это сделать print('слово найдено') 
  • Is the word searchable, is it a word? - Let's say Pie
  • @ Let'ssayPie, not, word the user enters the word - JackWolf
  • I understand that you need to compare the input word with a string from txt? - Let's say Pie
  • one
    Give an example of input and output data - Let's say Pie
  • Yes that's right. how it works for me (without a template): file content: cat, whaler input: whale output: word found - JackWolf

1 answer 1

Did I understand you correctly, given strict compliance?

 import re word = input() with open('first.txt', 'r') as file1: for line in file1.readlines(): if re.findall('^' + word + '$', line): print('Cлово найдено') else: print('Не найдено') 
  • one
    Yes, thank you very much! Just add, please correct the code, I confused you a little. import re word = input() with open('first.txt', 'r') as file1: for line in file1.readlines(): if re.findall(r'^' + word + '$', line): print('Cлово найдено') else: print('Не найдено') so that it goes to the end of the file) Thank you so much again! - JackWolf
  • According to the idea, if re.findall('^' + word + '$', line): if re.match(word, line): is completely replaced if re.match(word, line): - gil9red
  • @ gil9red, hmm, agree - Let's say Pie
  • In theory or not, re.match does not look for a full match with the string (only at the beginning), but re.fullmatch , yes. And here it is better to use not if re.findall('^' + word + '$', line) , but if re.search('^' + word + '$', line) or if re.match(word + '$', line) . - Wiktor Stribiżew