简体   繁体   中英

Help with multiline regex match

I am trying to have a regular expression match a value that spans multiple lines. I am using the re.S flag, but still get no results. Any ideas why?

This is the text that I am searching through:

<File id="abc.txt" EngRev="74">
  <Identifier id="STRING_ID" isArray="1" goesWith="3027253">
    <EngTranslation>"Value 1","Value 2","Value 3","Value 4","Value 5",</EngTranslation>
    <LangTranslation filename="abc.txt" key="STRING_ID 0">Value 1</LangTranslation>
    <array filename="abc.txt" key="STRING_ID 1">Value 2</array>
    <array filename="abc.txt" key="STRING_ID 2">Value 3</array>
    <array filename="abc.txt" key="STRING_ID 3">Value 4</array>
    <array filename="abc.txt" key="STRING_ID 4">Value 5</array>
  </Identifier>
  <Identifier id="STRING_ID2" isArray="0" goesWith="3027253">
    <EngTranslation>"Value 1"</EngTranslation>
    <LangTranslation filename="abc.txt" key="STRING_ID2">Value 1</LangTranslation>
  </Identifier>
</File>

This is the code I am using to obtain a match:

def updateToArray(matchobj):
     return matchobj.group(0).replace('LangTranslation','array')
outXML = re.sub(r'<Identifier.*?<array.*?</Identifier>', updateToArray, outXML, re.S)

I strongly urge you to not use regular expressions for parsing XML. SO has a lot of question/answer threads explaining why. For instance see this classic .

Since you are using Python why not use libraries like BeautifulSoup or Lxml to do the job much more cleanly and concisely?

You're missing an argument:

re.sub(pattern, repl, string[, , flags])

The flags appear to be integers, so it's treating re.S as the count argument. Using zero for count preserves the default behavior and allows you to pass the flags as the fifth argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM