Skip to main content
 首页 » 编程设计

Python 正则表达式 : What's wrong with this

2025年05月04日25zhengyun_ustc

我正在尝试做一个正则表达式来从这个 XML 中获取错误代码。

>>> re_code = re.compile(r'<errorcode>([0-9]+)</errorcode>', re.MULTILINE) 
>>> re_code.match('''<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?> 
... <methoderesponse> 
...     <status> 
...         <message/> 
...         <errorcode>515</errorcode> 
...         <value>ERROR</value> 
...     </status> 
... </methoderesponse> 
... ''') 

这应该很容易。但是我不明白为什么它不匹配。

请您参考如下方法:

.match() 尝试在开始时进行匹配。你想要 .search() 或者更有可能是 .findall()

虽然看一下 XML 解析器 - 使用 XPath 或等价物来获取数据要好得多(另外它会处理正则表达式不会处理的细微差别)

适用于您的示例 XML 的示例:

import xml.etree.ElementTree as ET 
tree = ET.fromstring(text) 
 
>>> tree.findall('.//errorcode')[0].text 
'515' 

关于 ElementTree here 的更多信息我会亲自查看 lxml