【问题标题】:Regex: Remove spaces in some punctuation [duplicate]正则表达式:删除某些标点符号中的空格[重复]
【发布时间】:2020-05-26 00:35:08
【问题描述】:

我有一些字符串,例如abc pre - school unitabc pre / school district,我需要在连字符和斜杠前后删除额外的空格。这些示例将变为abc pre-school unitabc pre/school district

我尝试了这个解决方案,但这只是用连字符替换斜杠或连字符。如何删除空格以获取这些字符串?

abc pre-school unit abc pre/school district

import re

text= ['abc pre - school unit', 'abc pre / school district']

for name in text:
    tmp= re.sub("\s+[-/]\s+" , "-", name)

    print(tmp)

【问题讨论】:

    标签: python regex


    【解决方案1】:

    您可以捕获该符号,然后用它替换:

    text = ['abc pre - school unit', 'abc pre / school district']
    
    for name in text:
        tmp = re.sub("\s+([/-])\s+" , "\\1", name)
        print(tmp)
    

    打印出来:

    abc pre-school unit
    abc pre/school district
    

    【讨论】:

      【解决方案2】:

      在 re.sub 中,您可以通过将其放在大括号中来捕获模式。您可以在替换中通过使用位置参数来引用它,例如 \1、\2、\3

      所以解决方案是: 对于文本中的名称: tmp.append(re.sub("\s+([-/])\s+" , "\1", name))

      【讨论】:

        【解决方案3】:

        在您的情况下,您也需要将其分配回去

        text= ['abc pre - school unit', 'abc pre / school district']
        tmp=[]
        for name in text:
            tmp.append(re.sub("\s+([-/])\s+" , r'\1', name))
        
        tmp
        ['abc pre-school unit', 'abc pre/school district']
        

        或者

        newlist=list(map(lambda x : re.sub("\s+([-/])\s+" , r'\1', x),text))
        

        【讨论】:

        • 您的答案中的Or 部分与我的相同,并且是在我发布后大量添加的。
        猜你喜欢
        • 2015-10-25
        • 1970-01-01
        • 2022-08-13
        • 2015-10-03
        • 1970-01-01
        • 1970-01-01
        • 2020-07-09
        • 1970-01-01
        • 2013-02-21
        相关资源
        最近更新 更多