用正则表达式删除单词中的空格,包括“&”号

时间:2019-10-03 05:08:21

标签: regex python-3.x regex-lookarounds regex-group

在python3中,使用re.sub(pattern, replacement, string),我能够删除&符号周围的空格。例如,以下短语应作如下修改:

A和D替代解决方案”到“ AD替代解决方案

WESTMOUNT管道加热”到“ WESTMOUNT管道加热

全景视图B和B ”到“全景视图BB”

我已经能够解决前两种模式,但是我遇到了第三种问题,我尝试了以下方法:

import re
#str="A & D ALTERNATIVE SOLUTIONS LTD."
#str="WESTMOUNT PLUMBING & HEATING LTD."
str= "A PANORAMIC VIEW B & B"


str = re.sub('(?<=\\&)\s','',str)
str = re.sub('(?<=^[A-Z])\s','',str)
str = re.sub('[^\w\s]','',str)

print(str)

如何获得所有图案?

1 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

strlist = ["A & D ALTERNATIVE SOLUTIONS LTD.","WESTMOUNT PLUMBING & HEATING LTD.", "A PANORAMIC VIEW B & B"] 
pattern = r'(\w{2}\s)?\s?& (\w{2})?'

 [re.sub(pattern,r'\1\2',str_) for str_ in strlist]
Out[120]: 
['AD ALTERNATIVE SOLUTIONS LTD.',
 'WESTMOUNT PLUMBING HEATING LTD.',
 'A PANORAMIC VIEW BB']