我无法理解 Python 中的正则表达式模块。我认为我想做的事情相当简单,但我想不通。
我需要搜索一些 xml 文件并找到这个模式:
'DisplayName="包裹 (10-1-2012)"'
我可以解析 xml 并进行替换没问题,我无法弄清楚的部分是如何进行通配符搜索以查找“包裹(某年)”的任何实例。由于日期会有所不同,我需要找到这种模式:
pat = '"Parcels (*-*-*)"'
我想用今天的日期替换它,我可以用时间模块来做。我复制了 80 个左右的 xml 文档中的一行,我需要在其中找到模式。
根据 re.search() 函数的帮助,似乎我可以输入一个模式,然后输入我希望搜索的字符串。但是,我遇到了错误。
帮助模块 re: 中的函数搜索:
搜索(模式、字符串、标志=0) 扫描字符串寻找与模式的匹配,返回 匹配对象,如果未找到匹配项,则为 None。
这是我的小测试片段:
import re
pat = '"Parcels (*-*-*)"'
t= ' <Layer DisplayName="Parcels (7-1-2010)" FeatureDescription="Owner Name: {OWNER_NAME}<br/>Property Address: {PROP_ADDR}<br/>Tax Name: {TAX_NAME}<br/>Tax Address 1: {TAX_ADD_L1}<br/>Tax Address 2: {TAX_ADD_L2}<br/>Land Use: {USE1_DESC}<br/><a href="http://www16.co.hennepin.mn.us/pins/pidresult.jsp?pid={PID_NO}">View Property Information</a><br/><br/><br/>" FeatureLabel="Parcel ID: {PID_NO}" IconUri="{RestVirtualDirectoryUrl}/Images/Parcel.png" Identifiable="true" IncludeInLayerList="true" IncludeInLegend="true" Name="Parcels" Searchable="true" ShowMapTips="true" UnconfiguredFieldsSearchable="true" UnconfiguredFieldsVisible="true" Visible="true">'
match = re.search(pat, t)
print match
大部分线路都是垃圾,我不需要担心。我只需要查看如何在该行中找到该日期,以便我可以在 replace() 函数中只使用该部分。有谁知道我如何找到这些日期? xml 某处可能还有其他日期,但我不需要替换这些;就在它说“包裹(某年)”的地方。感谢您的帮助!谢谢!
请您参考如下方法:
import re
t= ' <Layer DisplayName="Parcels (7-1-2010)" FeatureDescription="Owner Name: {OWNER_NAME}<br/>Property Address: {PROP_ADDR}<br/>Tax Name: {TAX_NAME}<br/>Tax Address 1: {TAX_ADD_L1}<br/>Tax Address 2: {TAX_ADD_L2}<br/>Land Use: {USE1_DESC}<br/><a href="http://www16.co.hennepin.mn.us/pins/pidresult.jsp?pid={PID_NO}">View Property Information</a><br/><br/><br/>" FeatureLabel="Parcel ID: {PID_NO}" IconUri="{RestVirtualDirectoryUrl}/Images/Parcel.png" Identifiable="true" IncludeInLayerList="true" IncludeInLegend="true" Name="Parcels" Searchable="true" ShowMapTips="true" UnconfiguredFieldsSearchable="true" UnconfiguredFieldsVisible="true" Visible="true">'
你需要转义括号然后你可以更具体的内容,通用字符是.,*表示0个或多个:
pat = '"Parcels \(.*\)"'
match = re.search(pat, t)
print(match.group())
打印:
"Parcels (7-1-2010)"
更具体的模式是:
pat = '"Parcels \([0-9]+-[0-9]+-[0-9]+\)"'
match = re.search(pat, t)
print(match.group())
打印:
"Parcels (7-1-2010)"
这里括号内容([0-9])统一描述了0到9的所有数字(\d等价),加上,+,跟在它们后面表示大于0,破折号表示它自己。
