Python re.sub use non-greedy mode (.*?) with end of string ($) it comes greedy!

前端 未结 2 1346
终归单人心
终归单人心 2021-01-12 17:52

Code:

str = \'

A
B\' print(re.sub(r\'\\w$\', \'\', str))

It is expected to return

2条回答
  •  被撕碎了的回忆
    2021-01-12 18:33

    The non-greediness won't start later on like that. It matches the first and will non-greedily match the rest, which actually need to go to the end of the string because you specify the $.

    To make it work the way you wanted, use

    /\w$/
    

    but usually, it is not recommended to use regex to parse HTML, as some attribute's value can have < or > in it.

提交回复
热议问题