Java 代码:使用正则表达式从字符串中提取省市区镇信息
以下是一个使用 Java 代码和正则表达式从字符串中提取省、市、区、镇信息的实现示例。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LocationExtractor {
private static final String PROVINCE_REGEX = "(?<province>[^省]+省)";
private static final String CITY_REGEX = "(?<city>[^市]+市)";
private static final String DISTRICT_REGEX = "(?<district>[^区]+区)";
private static final String TOWN_REGEX = "(?<town>[^镇]+镇)";
public static void main(String[] args) {
String input = "我住在湖北省武汉市洪山区关山大道123号";
Location location = extractLocation(input);
System.out.println(location);
// 输出:Location{province='湖北', city='武汉', district='洪山', town='关山大道'}
}
public static Location extractLocation(String input) {
String province = extractGroup(input, PROVINCE_REGEX, "province");
String city = extractGroup(input, CITY_REGEX, "city");
String district = extractGroup(input, DISTRICT_REGEX, "district");
String town = extractGroup(input, TOWN_REGEX, "town");
return new Location(province, city, district, town);
}
private static String extractGroup(String input, String regex, String groupName) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
return matcher.group(groupName);
} else {
return null;
}
}
}
class Location {
private String province;
private String city;
private String district;
private String town;
public Location(String province, String city, String district, String town) {
this.province = province;
this.city = city;
this.district = district;
this.town = town;
}
public String getProvince() {
return province;
}
public String getCity() {
return city;
}
public String getDistrict() {
return district;
}
public String getTown() {
return town;
}
@Override
public String toString() {
return "Location{" +
"province='" + province + "'"
+ ", city='" + city + "'"
+ ", district='" + district + "'"
+ ", town='" + town + "'"
+ "}";
}
}
注意:
这个实现是基于假设输入字符串中的省、市、区和镇名都不包含'省'、'市'、'区'和'镇'这些字符。如果输入字符串不符合这个假设,那么这个实现将无法正确提取位置信息。为了更准确地提取位置信息,需要更加复杂的正则表达式和算法。
更多信息:
原文地址: https://www.cveoy.top/t/topic/nw45 著作权归作者所有。请勿转载和采集!