Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

python - 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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...