Skip to content

Instantly share code, notes, and snippets.

@bestK
Created July 27, 2021 01:39
Show Gist options
  • Save bestK/b9ea05d3828e895d77e341e538236f11 to your computer and use it in GitHub Desktop.
Save bestK/b9ea05d3828e895d77e341e538236f11 to your computer and use it in GitHub Desktop.
Validator containerNumber
/**
* 是否为柜号
*
* @param containerNumber 输入值
* @return 真/假
*/
public static Boolean isContainerNumber(String containerNumber) {
if (containerNumber.length() == 11) {
String regEx = "^[a-zA-Z]{4}\\d{7}$";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(containerNumber);
if (!m.matches()) {
return false;
}
Map<String, Integer> dictionary = Maps.newHashMap();
int number = 10;
List<String> specials = Lists.newArrayList("B", "L", "V");
for (char i = 97; i <= 122; i++) {
String letter = String.valueOf(i).toUpperCase();
if (specials.contains(letter)) {
number++;
}
dictionary.put(letter, number++);
}
double sum = 0;
for (int i = 0; i < containerNumber.length() - 1; i++) {
String key = getSingleWord(containerNumber, i);
Integer temp = dictionary.get(key);
if (temp != null) {
sum += temp * Math.pow(2, i);
} else {
sum += Integer.parseInt(key) * Math.pow(2, i);
}
}
return Double.parseDouble(getSingleWord(containerNumber, containerNumber.length() - 1)) == (sum % 11) % 10;
}
return false;
}
/**
* 获取指定位置的单字
*
* @param value 字符串
* @param index 下标
* @return 单字
*/
public static String getSingleWord(String value, Integer index) {
return String.valueOf(value.toCharArray()[index]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment