This question already has an answer here:
How can I find all matches to a regular expression in Python?
                                
                                    (1个答案)
                                
                        
                                在8个月前关闭。
            
                    
我目前正在练习正则表达式。我声明了-> str1="bbccaa"。我希望结果是所有b和a,即“ bbaa”。我试过了->'[^ c] +',[ab] +但是我尝试的一切最终都给出了输出为'bb'。有人可以告诉我我要去哪里哪里以及解决方案吗?

最佳答案

尝试这个:

import re

s = "bbccaa"
print(re.sub("[^ab]+", r"", s))
#bbaa

10-06 01:55