首页 > 解决方案 > 使用Regex,python删除字符串中的所有数字

问题描述

我是正则表达式的新手。我正在尝试删除所有数字,但与响应相对应的数字应保留在整个字符串中,其余数字应被删除。例如,对应于响应的 892 和 762 应该在字符串中保持原样,并且当这些值再次出现在字符串中时,不应删除。但其余其他数字应删除。

mystr=" hey vi_pl12879 remove all the digits
        am_87284 remove all the digits except res value
        how are you response > 892
        omh 8241 del the digits 
        delete the manm/alka/8726/uh/the
        the code for error is 892
        response > 762
        keep only res values in the whole string
        error code may be 762"

预期结果:

mystr=" hey vi_ remove all the digits
        am_ remove all the digits except res value
        how are you response > 892
        omh  del the digits 
        delete the manm/alka//uh/the
        the code for error is 892
        response > 762
        keep only res values in the whole string
        error code may be 762"

标签: regexstringpython-3.x

解决方案


您可以使用正向查找来删除所有数字,但在第一个response >表达式之后的数字除外,您可以使用以下方法找到findall

import re

mystr=" hey vi_pl12879 remove all the digits\
 am_87284 remove all the digits except res value\
 how are you response > 892\
 omh 8241 del the digits\
 delete the manm/alka/8726/uh/the\
 the code for error is 892\
 response > 762\
 keep only res values in the whole string\
 error code may be 762"

response_groups = re.findall(r".+?(response > \d+)", mystr)

res = re.sub(
    r"\d(?=.+?" + response_groups[0] + ")",
    "",
    mystr
)

print(res)

这打印:

嘿 vi_pl 删除所有数字 am_ 删除除 res 值之外的所有数字 你如何响应 > 892 omh 8241 del 数字删除 manm/alka/8726/uh/错误代码是 892 响应 > 762 只保留 res 值整个字符串错误代码可能是 762


推荐阅读