首页 > 解决方案 > 使用 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

标签: pythonregex

解决方案


要解决这个问题,只需启用 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)

推荐阅读