小编JJL*_*JLL的帖子

Python正则表达式字符串同时匹配和替换

在Python中,有没有一种方法可以同时搜索、返回匹配的字符串和替换匹配的字符串?请参阅下面的示例:

a = "[fox] dog turtle [cat]"

目标:

result1 = "fox" #(first match inside bracket)
result2 = "cat" #(second match inside bracket)
result3 = "dog turtle" #(remaining string after removing matched text inside brackets
Run Code Online (Sandbox Code Playgroud)

我拥有的:

result1, result2 = re.findall('\[.*?\]', a)
result3 = re.sub('\[.*?\]', '', a)
Run Code Online (Sandbox Code Playgroud)

必须运行re两次似乎多余且笨重。有没有更优雅的方法来实现这一点?

python regex string replace python-3.x

3
推荐指数
1
解决办法
3056
查看次数

标签 统计

python ×1

python-3.x ×1

regex ×1

replace ×1

string ×1