tags:

views:

93

answers:

2

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)
+7  A: 

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?

Manoj Govindan
I'm only 7 days active at SO. But have noticed there's approximately one question per day about parsing XML or HTML by RE. It should be captured somewhere as common antipattern.
Odomontois
+1  A: 

You're missing an argument:

re.sub(pattern, repl, string[, count, 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.

Alan Moore