首页 > 解决方案 > 删除python中字符串中除下划线和大括号之外的所有标点符号?

问题描述

假设我有一个字符串

s = "Hey, {customer_name}, what's up?"

删除除下划线和花括号外的所有标点符号的适当正则表达式是什么?

标签: pythonregexpython-3.xregex-negation

解决方案


您可以使用re.subwith 模式[^\w _{}],它会忽略所有字母数字字符,但会包括下划线_和花括号{}

import re

s = "Hey, {customer_name}, what's up?"
print(re.sub(r'[^\w {}]','',s))

输出是Hey {customer_name} whats up


推荐阅读