python regex get last words of a text up to a stop word with re module (not regex module)

Viewed 29

I am after getting the last words of a text up to a stopword.

Imagine I have the text:

first_part = "This is a text that with the blue paper"

going from end back I would like to get "blue paper".

In order to do that I use the regex module

import regex as re
print(first_part)
result=re.search(r"(?r)(?<=(\s*\b(an|a|the|for)\b\s*))(?P<feature>.*?)(?=\s*)$",first_part)
print(result)

Regex explanation:
(?r) = reverse
(?<=(\s*\b(an|a|the|for)\b\s*)) =look behind any of the stop words with word boundary \b
(?P feature .?) = basically whatever .
$ = from the end of the string

This works just fine. but I am using the module regex in order to be able to use "(?r)" meaning reverse.

Anyone knows if it would be possible to do this using re? I need to implement this functionality with standard libraries functionalities.

1 Answers

If you add a greedy match in front and a lazy one in the back, you will just get the last words.. Not 100% sure this is what you want though.

>>> first_part = "This is a text that with the blue paper"
>>> m = re.match(r"(?:.*)(?:an|a|the|for)\W(.+?)$", first_part)
>>> m[1]
'blue paper'
Related