我在Python中工作,我有一些字符串包含特殊字符,比如
";我的名字是*,他是*。
我想找到字符串中的所有特殊字符并插入">\";在它之前,所以它应该是:
";我的名字是,他是。
我用来识别特殊字符的正则表达式是r'[-._!"`'#%&,:;<>=@{}~$()*+/\?[]^|]+'
。在Python中有一种简单的方法吗?
您需要替换为r'\g<0>'
:
import re
rx = r'[][._!"`'#%&,:;<>=@{}~$()*+/\?^|-]+'
text = "My name is * and he is *"
print( re.sub(rx, r'\g<0>', text) )
# => My name is * and he is *
请参阅Python演示。
更换模式详细信息:
\
-单个文字反斜杠(使用双反斜杠是因为在替换模式中很特殊(
g<0>
-对整个匹配值的反向引用
您只是用regex做得太过分了——一个简单的替换方法可以轻松地解决问题
示例:
string = "Hello my name is * I live in *nI am ^ years old I live with my %"
special_characters = ['*', '^', '%']
for char in special_characters:
string = string.replace(char, f'{char}')
print(string)
输出:
你好,我的名字是\*我住在\*
我已经岁了,我和我的住在一起