How do I find the shortest overlapping match using regular expressions?

前端 未结 9 1106
無奈伤痛
無奈伤痛 2020-12-15 08:03

I\'m still relatively new to regex. I\'m trying to find the shortest string of text that matches a particular pattern, but am having trouble if the shortest pattern is a sub

9条回答
  •  粉色の甜心
    2020-12-15 08:19

    Another regex solution; it finds only the last occurence of .*a.*b.*c:

    my_pattern = 'a(?!.*a.*b.*c).*b[^c]*c'
    

    a(?!.*a.*?b.*?c) ensures that there is no 'a.*?b.*?c' after first 'A' strings like A|A|B|C or A|B|A|B|C or A|B|C|A|B|C in results are eliminated

    b[^c]*c ensures that after 'B' there is only one 'C' strings like A|B|C|B|C or A|B|C|C in results are eliminated

    So you have the smallest matching 'a.*?b.*?c'

提交回复
热议问题