How to search for the last occurrence of a regular expression in a string in python?

后端 未结 3 2020
情深已故
情深已故 2021-01-02 03:52

In python, I can easily search for the first occurrence of a regex within a string like this:

import re
re.search(\"pattern\", \"target_text\")
3条回答
  •  执笔经年
    2021-01-02 04:40

    import re
    re.search("pattern(?!.*pattern)", "target_text")
    

    or

    import re
    re.findall("pattern", "target_text")[-1]
    

    You can use these 2 approaches.

    If you want positions use

    x="abc abc abc"
    print [(i.start(),i.end(),i.group()) for i in re.finditer(r"abc",x)][-1]
    

提交回复
热议问题