Python 为什么我不能使用re.sub替换组?
我的目标是使用Python 为什么我不能使用re.sub替换组?,python,regex,Python,Regex,我的目标是使用regex在字符串中找到一个组,并用空格替换它 我要寻找的组是一组符号,只有当它们落在字符串之间时。当我使用re.findall()时,它完全按照预期工作 word = 'This##Is # A # Test#' print(word) re.findall(r"[a-zA-Z\s]*([\$\#\%\!\s]*)[a-zA-Z]",word) >>> ['##', '# ', '# ', ''] 但是当我使用re.sub()时,它不是替换组,而是替换整个正则
regex
在字符串中找到一个组,并用空格替换它
我要寻找的组是一组符号,只有当它们落在字符串之间时。当我使用re.findall()
时,它完全按照预期工作
word = 'This##Is # A # Test#'
print(word)
re.findall(r"[a-zA-Z\s]*([\$\#\%\!\s]*)[a-zA-Z]",word)
>>> ['##', '# ', '# ', '']
但是当我使用re.sub()
时,它不是替换组,而是替换整个正则表达式
x = re.sub(r"[a-zA-Z\s]*([\$\#\%\!\s]*)[a-zA-Z]",r' ',word)
print(x)
>>> ' #'
如何使用正则表达式仅替换组?我预期的结果是:
'This Is A Test#'
您可以对要保留的模式部分进行分组,并在替换字符串中使用反向引用:
x = re.sub(r"([a-zA-Z\s]*)[\$\#\%\!\s]*([a-zA-Z])", r'\1 \2', word)
问题是你的正则表达式完全匹配错误的东西
x=re.sub(r'\b[$#%!\s]+\b','',word)
[$\35;%!\ s]*
同样很好,可读性更高#
,您可以使用更简单的表达式:
(?:[\s#](?!\Z))+
然后需要用空格替换,请参见。在Python中,这可能是:
import re
string = "This##Is # A # Test#"
rx = re.compile(r'(?:[\s#](?!\Z))+')
new_string = rx.sub(' ', string)
print(new_string)
# This Is A Test#