python - 正则表达式,用 NULL 替换所有数字,除了几个单词(单词可以有数字字符)
问题描述
用空字符串替换所有数字的正则表达式,除了几个单词(单词可以有数字字符)——python 例如要排除的单词:“cloud9”和“ec2”
cloud9 100 pesos dollars99 908908f098080 800 ec2
应转换为:
cloud9 pesos dollars f ec2
在python中试过这个:
\b(?!ignoreme23|43ignoreyou)\b\d+
测试上述表达式:
8 --> matches 8
8u9 --> matches 8 but not 9
100f --> matches 100
f100 --> does not match anything
999 --> matches all 9s
ignoreme23 --> ignores as required
ignoreme232323 --> ignores "ignoreme23" but does not match with the following "2323"
2434ignoreme23 --> matches 2334 ignores "ignoreme23" as required
23243ignoreyou --> matches 23243. Should only match 2324 and should ignore "43ignoreyou"
232 43ignoreyou --> matches 232 and ignores "43ignoreyou" as required
43ignoreyou --> ignores as required
尝试了不同的正则表达式,但似乎无法解决这个问题。
有什么见解吗?
解决方案
你可以试试这个简单的正则表达式
\d+[a-zA-Z]?\d+
要替换给定文本中的数字,请应用以下内容
re.sub(r'\d+[a-zA-Z]?\d+', '', giventext)
此函数根据正则表达式 \d+[a-zA-Z]?\d+ 将给定文本中的捕获值替换为函数的第二个参数,该参数是一个空字符串。
输出:- cloud9 比索美元 ec2
推荐阅读
- makefile - 使用带有 NMake 样式 Makefile 的 clang-cl 无法回显
- rust - How to fix Rust error "value used here after move"?
- flutter - 在图库视图网格中渲染应用内拍摄的照片
- java - 如何使用java在图中添加节点和叶值
- jetty - org.eclipse.jetty.io.FillInterest - 阻止读取挂起 - 原因是什么?
- javascript - 如何将数组的相应索引传递给onPress
- python - 为什么 Heroku 无法编译我的 python 应用程序?
- python - discord.py on_message 正在破坏机器人
- aws-lambda-edge - AWS Lambda@Edge 是否与 Lambda 共享所有可用的运行时?
- google-apps-script - 如何按谷歌表格中的两列过滤