【无标题】

获取地址中的省市区信息

  • 业务背景:获取地址中的省(市)、市(区)、区信息,直辖市则市名补充省名,区名补充市名
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)
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值