获取地址中的省市区信息
- 业务背景:获取地址中的省(市)、市(区)、区信息,直辖市则市名补充省名,区名补充市名
func extractLocationInfo(address string) (string, string, string) {
regex := `(?P<province>.*?(省|自治区|特别行政区|市))?(?P<city>.*?(市|区|县|旗))?(?P<district>.*?[区县])?`
r := regexp.MustCompile(regex)
matches := r.FindStringSubmatch(address)
province := ""
city := ""
district := ""
if len(matches) > 2 {
province = matches[1]
}
if len(matches) > 4 {
city = matches[3]
}
if len(matches) > 5 {
district = matches[5]
}
if province == "" && city != "" {
province = city
city = ""
}
if city == "" && district != "" {
city = district
district = ""
}
return province, city, district
}
func main() {
address1 := "广西壮族自治区南宁市兴宁区"
address2 := "湖北省恩施土家族苗族自治州恩施市"
address3 := "贵州省黔东南苗族侗族自治州凯里市"
address4 := "河南省商水县巴村镇住过村1组"
address5 := "内蒙古自治区兴安盟科尔沁右翼前旗"
address6 := "西藏自治区日喀则地区日喀则市"
address7 := "宁夏回族自治区银川市兴庆区"
address8 := "陕西省延安市宝塔区麦克大厦"
address9 := "北京市昌平区沙河镇于辛庄村李静家园"
province1, city1, district1 := extractLocationInfo(address1)
province2, city2, district2 := extractLocationInfo(address2)
province3, city3, district3 := extractLocationInfo(address3)
province4, city4, district4 := extractLocationInfo(address4)
province5, city5, district5 := extractLocationInfo(address5)
province6, city6, district6 := extractLocationInfo(address6)
province7, city7, district7 := extractLocationInfo(address7)
province8, city8, district8 := extractLocationInfo(address8)
province9, city9, district9 := extractLocationInfo(address9)
fmt.Println("地址1 - 省:", province1, " |市:", city1, " |区:", district1)
fmt.Println("地址2 - 省:", province2, " |市:", city2, " |区:", district2)
fmt.Println("地址3 - 省:", province3, " |市:", city3, " |区:", district3)
fmt.Println("地址4 - 省:", province4, " |市:", city4, " |区:", district4)
fmt.Println("地址5 - 省:", province5, " |市:", city5, " |区:", district5)
fmt.Println("地址6 - 省:", province6, " |市:", city6, " |区:", district6)
fmt.Println("地址7 - 省:", province7, " |市:", city7, " |区:", district7)
fmt.Println("地址8 - 省:", province8, " |市:", city8, " |区:", district8)
fmt.Println("地址9 - 省:", province9, " |市:", city9, " |区:", district9)
}