python - 输入地标或如果不匹配 foo 字符串
问题描述
假设我有一个文件,例如:
tata toto
tata titi
tata
如果我正在制作像这样的正则表达式:
^(tata) (toto)?
如果找到 toto,我希望 \2=toto,否则 \2=foo
所以我想输出:
tata toto
tata foo
tata foo
正则表达式可以吗?
解决方案
解决此问题的一种方法是用以下内容替换任何未tata
跟随的toto
内容tata foo
:
import re;
string = '''
tata toto
tata titi
tata
'''
print (re.sub('^tata(?! toto$).*$', 'tata foo', string, 0, re.M))
输出:
tata toto
tata foo
tata foo
推荐阅读
- mongodb - 使用查询字符串参数获取请求到(restdb)API 总是响应相同的答案,即使参数发生变化
- python - Python Tkinter GUI:单击按钮删除函数内定义的画布对象
- postgresql - 使用其他聚合函数的 PostgreSQL“直通”聚合函数
- docker - Neo4j 3.5.11 无法在 Docker 中启动
- javascript - 在 Visual Studio Code 中自定义组织导入
- c++ - 重新平衡时如何修复 AVL 删除操作中的分段错误?
- python - 调用 model.predict_classes() 后是否有可能获得预测精度?
- haskell - 在 do 表示法中使用 id
- r - 无法获取有关化学品饮用水标准的公共数据 - “无法加载 HTTP 资源”错误
- reactjs - 如何添加 ads.txt