从文件中删除带有特殊字符的多行图案

时间:2019-04-15 08:52:56

标签: python regex python-3.x

我需要从文件中删除多行模式。 例如:

  <Command name="somecom" type="type" >
     <input name="some input" />
     <output name="some output" />
  </Command>
  <?ignore <Command name="somecom" type="type" >
     <input name="some input" />
     <output name="some output" />
  </Command> ?> 

要删除的部分以

开头
 <?ignore

结尾为:

 ?>

我想使用正则表达式来做到这一点。 python3.6.3

with open('graph.xml', 'r') as readXML:
    tempFile = readXML.read()
    patr = re.compile("<?ignore.*?>", re.MULTILINE)
    tempFile = re.sub(patr,"",tempFile)
    print(tempFile)

结果:

  <Command name="somecom" type="type" >
     <input name="some input" />
     <output name="some output" />
  </Command>
  <?
     <input name="some input" />
     <output name="some output" />
  </Command> ?> 

我希望删除所有部分,而不仅仅是第一行的一部分。

4 个答案:

答案 0 :(得分:1)

您可以使用修饰符(?s)使点与换行符匹配,并跳过问号\?使其与字面上匹配。您可能还会使点开始方法变得非贪婪.*?

(?s)<\?ignore.*?\?>

Regex demo | Python demo

或者,您也可以使用重复模式以负前瞻方式匹配不包含?>的行:

<\?ignore\b.*\n(?!.*\?>)(?:.*\n)*.*\?>
  • <\?ignore\b.*\n匹配<?ignore,其后跟任意字符的1+倍,后跟换行符
  • (?!.*\?>)负向前进,断言右边的不是?>
  • (?:.*\n)*重复0次以上,与除换行符后跟换行符的所有字符匹配
  • .*\?>匹配0+次任何字符和?>

Regex demo | Python demo

答案 1 :(得分:1)

您可以使用<\?ignore.+?\?>模式删除多行模式:

示例:

import re

str = """
  <Command name="somecom" type="type" >
     <input name="some input" />
     <output name="some output" />
  </Command>
  <?ignore <Command name="somecom" type="type" >
     <input name="some input" />
     <output name="some output" />
  </Command> ?> 
  """

print(re.sub(r'<\?ignore.+?\?>', '', str, flags=re.MULTILINE|re.DOTALL))

打印输出:

  <Command name="somecom" type="type" >
     <input name="some input" />
     <output name="some output" />
  </Command>

请不要忘记使用这些标志,否则替换将无法进行:

flags=re.MULTILINE|re.DOTALL

答案 2 :(得分:0)

?是正则表达式中的可选量词,因此a?表示字符a是可选的。要从字面上检测出此字符,您需要对其进行转义。

尝试

<\?ignore.*\?>

答案 3 :(得分:0)

这是因为?影响“贪婪”的量词:*和+以使其变得“懒惰”的方式-*和+开始搜索在它们之后的字符/组的首次出现,然后匹配并返回。因此,要使您的正则表达式正常工作,您只需要转义?带有\

的符号

SetupOption(view.findViewById(R.id.optMyCash), R.drawable.ic_my_cash, getString(R.string.title_my_cash), onClickListener); SetupOption(view.findViewById(R.id.optHistory), R.drawable.ic_history, getString(R.string.title_history), onClickListener); SetupOption(view.findViewById(R.id.optAnnouncement), R.drawable.ic_announce, getString(R.string.title_announce), onClickListener); // and so on... 将按预期工作。