我有一个正则表达式,可以从数据中提取地址。 正则表达式查找“地址|地址|等等。'并选择地址,直到遇到4位数的邮政编码为止。 有时,在地址的开头添加了_,-等特殊字符。我需要代码来忽略第一个字母数字字符之前的特殊字符。
到目前为止,我运行了一个循环以排除所有特殊字符,如下面的代码所示。我需要代码仅删除出现在第一个字母数字字符前面的特殊字符。
输入(来自图像上的OCR):
服务地址—_Unit8-10 LEWIS St,BERRI,SA 5343
possible_addresses = list(re.findall('Address(.* \d{4}|)|address(.*\d{4})|address(.*)', data))
address = str(possible_addresses[0])
for k in address.split("\n"):
if k != ['(A-Za-Z0-9)']:
address_2 = re.sub(r"[^a-zA-Z0-9]+", ' ', k)
现在获得:
地址:—_Unit 8-10 LEWIS ST,BERRI SA 5343
地址_2:8单元10 LEWIS ST BERRI SA 5343
答案 0 :(得分:1)
[\W_]*
捕获特殊字符。
import re
data='Service address —_Unit8-10 LEWIS St, BERRI,SA 5343'
possible_addresses = re.search('address[\W_]*(.*?\d{4})', data,re.I)
address = possible_addresses[1]
print('Address : ' address)
地址:SA 5343,BERRI,LEWIS St8-10单位
答案 1 :(得分:0)
我猜想我们希望在此处设计的表达式应该将address
到四位数的zip刷掉,不包括诸如_
之类的某些已定义字符。然后让我们从带有i
标志的简单表达式开始,例如:
(address:)[^_]*|[^_]*\d{4}
我们不希望有的任何字符都将进入[^_]
。例如,如果我们排除!
,则表达式将变为:
(address:)[^_!]*|[^_!]*\d{4}
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"(address:)[^_]*|[^_]*\d{4}"
test_str = ("Address: Unit 8 - 10 LEWIS ST, BERRI SA 5343 \n"
"Address: Got now: __Unit 8 - 10 LEWIS ST, BERRI SA 5343\n"
"aDDress: Unit 8 10 LEWIS ST BERRI SA 5343\n"
"address: any special chars here !@#$%^&*( 5343\n"
"address: any special chars here !@#$%^&*( 5343")
matches = re.finditer(regex, test_str, re.MULTILINE | re.IGNORECASE)
for matchNum, match in enumerate(matches, start=1):
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
for groupNum in range(0, len(match.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.