Hi Everyone,

Do you know how i can get the values using Regular Expression between the opening and closing tags of xml files? I need to process xml files using python and i just need to get the values between tags.
For example:

<name value>my name is </name value>

i just need to get the value my name is using regular expression.
can someone help me with this?

thanks!

Dani AI

Generated

— the example you posted, <name value>my name is </name value>, is not well-formed XML: tag names cannot contain spaces and attributes must be written as attr="value". Two valid alternatives are either an element with text:
<name>my name is</name>
or an element with an attribute:
<name value="my name is" />.

As demonstrated, a quick regex can pull text from a toy string, but and are right to warn that regexes break on real XML (nested tags, namespaces, CDATA, line breaks, malformed input, etc.). Prefer a real parser. The standard, simple option in Python is xml.etree.ElementTree:

import xml.etree.ElementTree as ET

xml = '<root><name>my name is</name></root>'
root = ET.fromstring(xml)
print(root.find('name').text)   # -> my name is

If the value was an attribute instead:

xml = '<root><name value="my name is"/></root>'
root = ET.fromstring(xml)
print(root.find('name').get('value'))  # -> my name is

If parsing untrusted or broken HTML/XML, use a tolerant parser (BeautifulSoup) or a full-featured library (lxml). For large files, use ET.iterparse() or lxml.iterparse() to stream. Always wrap parsing in try/except to catch ET.ParseError.

If a regex is absolutely required (very constrained, guaranteed format), use a tag-specific, non-greedy pattern and DOTALL — but treat it as a brittle hack:

m = re.search(r'<name\b[^>]*>(.*?)</name>', text, re.DOTALL)
if m:
    print(m.group(1))

Checklist before choosing regex: confirm well-formed XML, no nested same tags, no namespaces, and no CDATA. Otherwise, use a parser.

Recommended Answers

All 4 Replies

import re

target = '<name value>my name is</name value>'
mobj = re.search('<.*>(.*)</.*>', target)
print mobj.groups()[0]

hi cghtkh!

thanks for your answer!

import re

target = '<name value>my name is</name value>'
mobj = re.search('<.*>(.*)</.*>', target)
print mobj.groups()[0]

Quote from stack overflow:

"asking regexes to parse arbitrary HTML is like asking Paris Hilton to write an operating system"

so it may not be the right tool... (Not meaning that I could write an OS either).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.