Python 正则表达式替换部分字符串

Python Regex replace part of string

我正在尝试替换字符串的特定部分。每次我有一个反斜杠后跟一个大写字母时,我都希望将反斜杠替换为制表符。就像在这种情况下:

Hello/My daugher/son

输出应该类似于

Hello    My daugher/son

我试过使用 re.sub():

for x in a:
    x = re.sub('\/[A-Z]', '\t[A-Z]', x)

但随后我的输出变为:

Hello    [A-Z]y daugher/son

这真的不是我想要的。有没有更好的方法来解决这个问题,也许不是在正则表达式中?

您可以将 /(?=[A-Z]) 替换为 \t。请注意,在 Python 中,您不需要将 / 转义为 \/

检查此 Python 代码,

import re 

s = 'Hello/My daugher/son'
print(re.sub(r'/(?=[A-Z])',r'\t',s))

打印,

Hello   My daugher/son

或者,按照您尝试替换的方式,您需要使用 /([A-Z]) 正则表达式捕获组中的大写字母,然后将其替换为 \t 以恢复组 1 中捕获的内容.检查此 Python 个代码,

import re 

s = 'Hello/My daugher/son'
print(re.sub(r'/([A-Z])',r'\t',s))

再次打印,

Hello   My daugher/son