regex - 使用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"
解决方案
您可以使用正向查找来删除所有数字,但在第一个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
推荐阅读
- reactjs - 持久存储不适用于 user_id 但适用于 access_token
- android - 使用 MapBox 的传单地图无法在 Android 中正确显示
- r - 如何处理 x 必须是相关图中的数字误差?
- html - 如何在电脑和手机上显示相同的字体粗细?
- c - Chez Scheme 中的 FFI,用于具有可变参数 (varargs) 的 C 函数
- vue.js - 通过点击卡片通过 v-dialog 编辑记录
- php - 如何将存储在数据库中的 url 重定向到 http 或 https
- mongodb - 如何安排猫鼬某个地方的营业时间?
- python - TypeError:接受 1 个位置参数,但给出了 2 个
- ios - UICollectionViewHeader - 计算复杂视图的大小