Search code examples
regexpython-2.7sentence

ReGex - Python - From word till the first dot in a sentencce


text = "hello there. I would like to capture from this point till the end"
capture= re.findall(r'(point).$',text)
print (capture)

Can someone tell me what did I do wrong here? Thank you.


Solution

  • Assuming you want to capture everything after a certain word till the next dot or the end of the string:

    point(.*?)(?:\.|$)
    

    Here, the (.*?) is a capturing group matching any characters 0 or more number of times in a non-greedy fashion. (?:\.|$) is a non-capturing group matching either a dot or an end of the string.

    Demo:

    >>> re.findall(r'point(.*?)(?:\.|$)', "hello there. I would like to capture from this point till the end")
    [' till the end']
    >>> re.findall(r'point(.*?)(?:\.|$)', "hello there. I would like to capture from this point till the end of the sentence. And now there is something else here.")
    [' till the end of the sentence']