简体   繁体   中英

How can I search for a substring that is between two values ​of a string in python?

someone who can give me an idea about doing the following: I have a text file of a single line but they send me several data, all as if it were xml but within a txt. ej:

<Respuesta><ResultEnviado><Resultado><Entrega>00123</Entrega><Refer>MueblesHiroshima</Refer><Item>34</Item><Valor>780</Valor></Resultado></ResultEnviado><EntregaItemResulados><EntregaItem><ItemId>123</ItemId><NameItem>MuebleSala</NameItem><ValorItem>180</ValorItem></EntregaItem><EntregaItem><ItemId>124</ItemId><NameItem>MuebleComedor</NameItem>ValorItem>200</ValorItem></EntregaItem><EntregaItem><ItemId>125</ItemId><NameItem>Cama</NameItem>ValorItem>200</ValorItem></EntregaItem><EntregaItem><ItemId>126</ItemId><NameItem>escritorio</NameItem>ValorItem>200</ValorItem></EntregaItem></EntregaItemResulados></Respuesta>

As you could see, it is a file with the extension txt.

<ResultEnviado><Resultado><Entrega>1213255654</Entrega><Refer>MueblesHiroshima</Refer><Item>34</Item><Valor>780</Valor></Resultado></ResultEnviado>

I am using python for the exercise.

Thank you very much for your comments or ideas.

Here we can use regular expressions .search() and .match() functions to find everything between the set tags. Note you need to import regular expression using the import re .

More info on regular expressions in python: here

import re

#open the file and read it
path = "C:/temp/file.txt"
with open(path, "r") as f:
    text = f.read()

#we use regular experssion to find everything between the tags
match = re.search("<ResultEnviado>(.*?)</ResultEnviado>", text)

#prints the text if it matches
if match:
    print(match.group(1))
else:
    print("No match found.")

this prints:

<Resultado><Entrega>00123</Entrega><Refer>MueblesHiroshima</Refer><Item>34</Item><Valor>780</Valor></Resultado>

Please let me know if you need any more help.

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