【问题标题】:Is there a regex, to replace the digits in the string with # and remove all the characters which are not digits [duplicate]是否有正则表达式,用#替换字符串中的数字并删除所有不是数字的字符[重复]
【发布时间】:2019-07-12 12:56:15
【问题描述】:

我有一个包含数字的字符串,我们需要删除所有不是数字的字符并将数字替换为#

我写了一个正则表达式,它可以用#替换数字,但是我找不到正则表达式来删除不是数字的字符。

import re
def replace_digits(string):
    m=re.sub("\d","#",string)

例子:

234 -> ###

a2b3c4 -> ###

abc -> <empty string>

#2a$#b%c%561# -> ####

【问题讨论】:

  • Ex 1:A = 234 输出:### Ex 2:A = a2b3c4 输出:### Ex 3:A = abc 输出:(空字符串)Ex 5:A = #2a$ #b%c%561# 输出:####
  • 您是否有特定原因要使用正则表达式?看起来可以轻松完成:'#' * len(x for x in s if x.isdigit())

标签: python regex python-3.x


【解决方案1】:
import re

examples = ['234',
'a2b3c4',
'abc',
'#2a$#b%c%561#']

for example in examples:
    new_s = '#' * len(re.sub(r'\D', '', example))
    print('Input = {} Output = {}'.format(example, new_s))

打印:

Input = 234 Output = ###
Input = a2b3c4 Output = ###
Input = abc Output = 
Input = #2a$#b%c%561# Output = ####

编辑(没有正则表达式 - 感谢@CorentinLimier)

for example in examples:
    new_s = ''.join('#' for c in example if c.isdigit())
    print('Input = {} Output = {}'.format(example, new_s))

编辑(添加来自 cmets 的 @Tomerikoo 的回答):

for example in examples:
    new_s = '#' * len([x for x in example if x.isdigit()])
    print('Input = {} Output = {}'.format(example, new_s))

【讨论】:

  • 不需要在组内使用元序列。而不是[^\d],只需使用\D
  • Imo 有一种更 Pythonic 的方式来编写你的想法 ''.join('#' if c.isdigit() else '' for c in s) 它更具可读性
  • @AndrejKesely Tomerikoos 上述 cmets 中的非正则表达式解决方案可能比 Corentin 建议的非正则表达式解决方案更具可读性(并且由于它不使用 ((,因此对初学者来说不太容易混淆)。跨度>
  • @Error-SyntacticalRemorse 将其添加到响应中。但我稍微编辑了一下——你不能在普通的生成器表达式上做len(),所以我把它括在[]
  • @AndrejKesely 谢谢。我不确定是否有必要,因为我知道例如打印可以省略。至于@CorentinLimier 的版本,我相信可以通过删除 else 部分并将 if 移到末尾来简化它:''.join('#' for c in example if c.isdigit())
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 2012-04-26
  • 2014-04-01
  • 2016-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多