python - 使用 REGEX Python 删除特定字符后的行
问题描述
我正在尝试使用 Python 中的 REGEX 和列表字符之后的行删除特定字符。
例如:
First Name:
Eric
我想删除“名字:”和“埃里克”,但留下后面的内容。
能否请你帮忙?这只是删除了第一行:
remove_list = ["First Name", "Last Name", "Age"]
for i in remove_list:
rmv_regex = re.compile("(?m)^"+ i + ".*\n" +".*\n", re.IGNORECASE) # Ignore case, regex of lines that start with the keywords
解决方案
要解决这个问题,只需启用 re.MULTILINE。例如在本文中:
First Name:
Eric
Last Name:
Dirkson
Age:
34
解决这个问题:
remove_list = ["First Name", "Last Name", "Age"]
for i in remove_list:
rmv_regex = re.compile("(?m)^"+ i + ".*\n"+ ".*\n", re.IGNORECASE | re.MULTILINE)
text = rmv_regex.sub('', text)
推荐阅读
- c++ - 变量在循环中显示但不在循环中
- php - Laravel 的关系返回不准确的结果
- java - 将 100 万条记录从 XLS 文件写入 Java 中的 CVS 文件
- ansible - 在角色下的剧本中设置标签的ansible语法错误
- c - const 字符串的 const 数组和错误“不是编译时常量”
- python-3.x - spyne + 扭曲的主机 b'localhost'
- flutter - 颤振:SingleChildScrollView 不可滚动
- regex - 谷歌表格正则表达式在每个单元格中保留部分文本
- bash - 在文件中查找行,获取该行的子字符串并替换为另一个字符串
- python - 导入 csv 文件时多次打印页眉信息