Given a string and character offsets inside that string, can I search in reverse order with Python regex?
The real problem I'm trying to solve is getting the appropriate phrase at a specific offset within the string, but I need to match the first instance before this offset.
In a situation where I have a regular expression that one character is long (ex: word boundary), I use a solution in which I change the line.
my_string = "Thanks for looking at my question, StackOverflow." offset = 30 boundary = re.compile(r'\b') end = boundary.search(my_string, offset) end_boundary = end.start() end_boundary
Output: 33
end = boundary.search(my_string[::-1], len(my_string) - offset - 1) start_boundary = len(my_string) - end.start() start_boundary
Output: 25
my_string[start_boundary:end_boundary]
Exit: "question"
However, this βreverseβ method will not work if I have a more complex regular expression that can include multiple characters. For example, if I wanted to match the first instance of "ing" that appears before the specified offset:
my_new_string = "Looking feeding dancing prancing" offset = 16 # on the word dancing m = re.match(r'(.*?ing)', my_new_string) # Except looking backwards
Ideal way out: power
I can probably use other approaches (split the file into lines and scroll backward), but using a regex back seems conceptually a simpler solution.
Irwin
source share