REGEX表达式,用于查找不同国家/地区的收货地址



我正试图从商业发票中提取发货地址。

一张商业发票的目的地为新加坡。另一张发票的目的地为香港

如何编写正则表达式以提取以新加坡或香港结尾的目的地地址?

我写了一个正则表达式来从商业发票中提取发货地址。见下文:

shipto = re.findall("Shipped To/FRT Forwardern[a-zA-Z0-9s#-,]*SINGAPORE", text). 

我的问题是发货地址可能是新加坡、香港或其他地方。如何使正则表达式更通用?

例如:我的发货地址可能是XXXX新加坡

YYYY香港

如何实现";或者"或";地址提取中REGEX中的逻辑?

我发现这个链接很有用。

以下是您将如何搜索";"香港";或";新加坡";。

shipto = re.findall("Shipped To/FRT Forwardern[a-zA-Z0-9s#-,]*(SINGAPORE|HONG KONG)", text)

如果你想概括,你可以这样做:

shipto_regular_expression_template = "Shipped To/FRT Forwardern[a-zA-Z0-9s#-,]*(LOCATIONS)"
# You could get your list of locations from anywhere.
# These locations will be treated as regular expressions. themselves
list_of_locations = ["SINGAPORE", "HONG KONG", "ELSEWHERE"]
list_of_locations_joined = "|".join(list_of_locations)
shipto_regular_expression = shipto_regular_expression_template.replace("LOCATIONS", list_of_locations_joined)
re.findall(shipto_regular_expression_template, text)

最新更新