regex 用空格替换数字中除句点以外的字符

m4pnthwp  于 2023-02-25  发布在  其他
关注(0)|答案(2)|浏览(124)

我目前有这个功能来替换特定的不需要的字符。句号也包括在内。但是我不想替换那些数字中的字符。

description = description.strip()
replace_characters = "(){}[].*;?/'-&!,\""
for character in replace_characters:
    description = description .replace(ch, " ")

我试过这个方法,但是我不能在regex中添加剩余的替换字符。

regex_str = r'(?<!\d)[.,;:](?!\d)'
list_amount = re.sub(regex_str, " ", description)

测试用例。注解是所需的输出

description = {2.4 oz/week.} #2.4 oz week
description = [yearly.] #yearly
description = (Current every day); #Current every day
mnowg1ta

mnowg1ta1#

您可以使用

re.sub(r'''[(){}[\]*;?/'&!,"-]|\.(?!(?<=\d.)\d)''', ' ', description)

请参见regex demo。* 详细信息 *:

  • [(){}[\]*;?/'&!,"-]-(){}[]*;?/'&!,"-列表中的一个字符(注意字符类末尾转义的]-,以及此处没有点)
  • |-或
  • \.(?!(?<=\d.)\d)-后面没有紧跟数字的.,该数字前面紧跟数字+.

请参见Python demo

import re
description = "{2.4 oz/week.}".strip()
description = re.sub(r'''[(){}[\]*;?/'&!,"-]|\.(?!(?<=\d.)\d)''', ' ', description)
print(description.strip()) # => 2.4 oz week
nbysray5

nbysray52#

试试这个:

regex = r"(?<!\d)[\(\)\{\}\[\].*;?/'\-&!,\\\"](?!\d)"

test_str = ("2.4 oz/week. 5.\n"
    "[yearly.]\n"
    "(Current every day);")

subst = " "

result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

相关问题