0

Actually my aim is to find a string in a file in python, I used regex to find it, I found it also but don't know how to calculate the coordinates of the position of that string in the file? I have no idea about it how to progress further

1 Answers1

1

You can use result.start() and result.end() to find out coordinates of regex match:

import re  # regex module

content = open('file.txt', 'r').read()  # read file
regex = r'regular expression here'

result = re.match(regex, content)  # find match

print(result.start(), result.end())  # print coordinates

Also, you can use result.span() to get tuple of start and end of match (thanks @JennevanderMeer for complement)

Vlad Havriuk
  • 1,291
  • 17
  • 29
  • 1
    There is also `result.span()` it is all detailed in https://docs.python.org/howto/regex.html#performing-matches – Jenne Jun 12 '20 at 08:36
  • Thank you very much to make an attempt to help me, actually, I want to get the coordinates on the screen of that particular string. –  Jun 12 '20 at 11:00
  • @ANKURag sorry, but it's a bit unclear to me, what exactly you are trying to do... – Vlad Havriuk Jun 12 '20 at 20:21
  • actually I am trying to build a GUI using tkinter in that I am searching for a specific string that I found also using regex but the problem is that it should show line number of that particular string and also through pop up i should show it ans when i click there it should direct me to the position in the file where i found that string –  Jun 13 '20 at 02:26