【问题标题】:Python re expression - remove # followed by numbers up until a commaPython re 表达式 - 删除 # 后跟数字直到逗号
【发布时间】:2021-11-04 02:04:26
【问题描述】:

我有一个字符串:

5956 Executive Dr #101, Fitchburg, WI 53719

我希望它是:

5956 Executive Dr, Fitchburg, WI 53719

我试过了:

string2 = re.sub("(\\.*)\\s+#.*", "\\1", string1)

但这只是让我明白:

5956 Executive Dr

如何在 Python 中做到这一点?我发现 re 表达式很混乱。理想情况下,我想对 Apt、Unit 等做同样的事情 - 用“”替换任何实例,如“Apt 3”、“Unit 3”、“Suite 4”。

【问题讨论】:

    标签: python substring python-re


    【解决方案1】:

    我认为你的方法在这里不是最好的,你可以使用更简单的表达方式:

    string2 = re.sub("\s#\d+", "", string1)
    
    • \s - 空格
    • # - 字面量 octothorpe
    • \d+ - 至少一位数

    要同时删除其他部分,您可以使用"(Apt|Unit|Suite)\s\d+" 或一起使用"\s#\d+|(Apt|Unit|Suite)\s\d+"

    【讨论】:

    • 感谢 Nullman!你能解释一下 1) octothorpe 和 2) /d+ 到底在做什么吗?这对我有用。
    • 您的文本中有类似#101 的内容。 octothorpe 也称为标签或磅,它是 # 符号。 \d 平均数字 (0-9) + 表示“至少一个”,所以 \d+ 会捕捉到 32425234412342 之类的东西
    猜你喜欢
    • 1970-01-01
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多