Python re.sub use non-greedy mode (.*?) with end of string ($) it comes greedy!
问题 Code: str = '<br><br />A<br />B' print(re.sub(r'<br.*?>\w$', '', str)) It is expected to return <br><br />A , but it returns an empty string '' ! Any suggestion? 回答1: Greediness works from left to right, but not otherwise. It basically means "don't match unless you failed to match". Here's what's going on: The regex engine matches <br at the start of the string. .*? is ignored for now, it is lazy. Try to match > , and succeeds. Try to match \w and fails. Now it's interesting - the engine