Python regex lookbehind and lookahead

后端 未结 2 863
南方客
南方客 2020-12-18 05:11

I need to match the string \"foo\" from a string with this format:

string = \"/foo/boo/poo\"

I tied this code:

poo = \"poo\         


        
相关标签:
2条回答
  • 2020-12-18 05:32

    Hey try the following regex:

    (?<=/).*(?=/poo)
    ^^^^^^
    

    It will not take into account your first slash in the result.

    Tested regex101: https://regex101.com/r/yzMkTg/1

    Transform your code in the following way and it should work:

    poo = "poo"
    foo = re.match('(?<=/).*(?=/' + re.escape(poo) + ')', string).group(0)
    

    Have a quick look at this link for more information about the behavior of Positive lookahead and Positive lookbehind

    http://www.rexegg.com/regex-quickstart.html

    0 讨论(0)
  • 2020-12-18 05:44

    You are missing a < in your lookbehind!

    Lookbehinds look like this:

    (?<=...)
    

    not like this:

    (?=...)
    

    That would be a lookahead!

    So,

    (?<=/).*(?=/poo)
    
    0 讨论(0)
提交回复
热议问题