支持最新版新能源、各類特種車等車牌號規則效驗
private static final Pattern pattern = Pattern.compile("^([京津滬渝冀豫云遼黑湘皖魯新蘇浙贛鄂桂甘晉蒙陜吉閩貴粵青藏川寧瓊使領A-Z]{1}[a-zA-Z](([京津滬渝冀豫云遼黑湘皖魯新蘇浙贛鄂桂甘晉蒙陜吉閩貴粵青藏川寧瓊ABCDEFGHJK]((?![IO])[a-zA-Z0-9](?![IO]))[0-9]{4})|([0-9]{5}[ABCDEFGHJK]))|[京津滬渝冀豫云遼黑湘皖魯新蘇浙贛鄂桂甘晉蒙陜吉閩貴粵青藏川寧瓊使領A-Z0-9]{1}[A-Z0-9]{1}[A-Z0-9應]{4,5}[A-Z0-9掛學警港澳領使急]{1})$");
1.通過正則表達式,能過來大量車牌號長度、字符規則不對的數據;例如:民航車牌,在正則表達式中沒有進行匹配 ;
2:實際使用中,黑色車牌通常為使領館、港澳地區車輛,通過正則表達式驗證通過后,還需要進行顏色效驗;
public class TestUtil {private static final String BLACK_RULE = "使領港澳";private static final Pattern pattern = Pattern.compile("^([京津滬渝冀豫云遼黑湘皖魯新蘇浙贛鄂桂甘晉蒙陜吉閩貴粵青藏川寧瓊使領A-Z]{1}[a-zA-Z](([京津滬渝冀豫云遼黑湘皖魯新蘇浙贛鄂桂甘晉蒙陜吉閩貴粵青藏川寧瓊ABCDEFGHJK]((?![IO])[a-zA-Z0-9](?![IO]))[0-9]{4})|([0-9]{5}[ABCDEFGHJK]))|[京津滬渝冀豫云遼黑湘皖魯新蘇浙贛鄂桂甘晉蒙陜吉閩貴粵青藏川寧瓊使領A-Z0-9]{1}[A-Z0-9]{1}[A-Z0-9應]{4,5}[A-Z0-9掛學警港澳領使急]{1})$");private static final Pattern whitePattern = Pattern.compile("^[0-9A-Za-z]{6,8}$");public static boolean isCarNo(String carNo, String color) {//通過號碼規則校驗,該規則能過濾大量民航、新能源車牌、車牌長度不對的車牌號boolean carNoRule = pattern.matcher(carNo).matches();if (!carNoRule) {return false;}//藍牌、黃牌長度一定為7位if (StringUtils.equals(color, ColorEnum.blue.name())|| StringUtils.equals(color, ColorEnum.yellow.name())) {return carNo.length() == 7;}//新能源車牌,長度為8位過濾規則if (StringUtils.equals(color, ColorEnum.small_new_energy.name())|| StringUtils.equals(color, ColorEnum.large_new_energy.name())) {return carNo.length() == 8;}//黑牌一定含有使領港澳if (StringUtils.equals(color, ColorEnum.black.name())) {return StringUtils.containsAny(carNo, BLACK_RULE);} else if (StringUtils.containsAny(carNo, BLACK_RULE)) {return false;}//白牌 警或應急結尾 WJ開頭 純字母+數字if (StringUtils.equals(color, ColorEnum.white.name())) {return carNo.endsWith("警") || carNo.startsWith("WJ") || carNo.endsWith("應急") || whitePattern.matcher(carNo).matches();}//其他顏色待補充return true;}public static void main(String[] args) {List<String> licenses = new ArrayList<>();licenses.add("湘JJ16871");licenses.add("粵HD666學");licenses.add("粵ZD677港");licenses.add("粵ZD000澳");licenses.add("滬19674領");licenses.add("258043使");licenses.add("贛A5330警");licenses.add("WJ鄂D4020"); licenses.add("京A33388D");licenses.add("民航1211");licenses.add("冀RR527掛");licenses.add("京X535應急");licenses.add("京X5359應急");licenses.add("皖0619940");licenses.add("吉0759703");licenses.add("民航B0150");licenses.add("LW92110");licenses.add("VAD1137");licenses.add("BAD00ss04");licenses.add("京HAD0057");licenses.add("京BDF9992");licenses.add("京00000V");for (String str : licenses) {System.out.println(str + ": " + isCarNo(str, "green"));}}