根据网络整理,经过实际应用。
package com.brofe.util;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
/**
* 校验全国组织机构代码是否合法
*
* <p>
* 本标准根据国家技术监督局 1997年国家标准制修订项目补充计划,对 GB/T 11714—1995《全国组织机构代码编制规则》进行修订。
* </p>
*
* <p>
* 使用方法: OrgCodeValidation.validate("全国组织机构代码");
* </p>
*
* @author brofe
* @since Jun 8, 2009
* @version 1.0
*/
public class OrgCodeValidation {
protected static Logger log = Logger.getLogger(OrgCodeValidation.class);
private static final String[] codeNo = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B",
"C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X", "Y", "Z" };
private static final String[] staVal = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11",
"12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24",
"25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35" };
private OrgCodeValidation () {}
/**
* 校验组织机构代码
*
* @param orgCode 待校验的组织机构代码
* @return true 表示合法,false 表示不合法
*/
public static boolean validate(String orgCode) {
if (StringUtils.isEmpty(orgCode)) {
log.error("组织机构代码不能为空", new NullPointerException());
return false;
}
Pattern pat = Pattern.compile("^[0-9A-Z]{8}-[0-9X]$");
Matcher matcher = pat.matcher(orgCode);
if (!matcher.matches()) {
return false;
}
Map map = new HashMap();
for (int i = 0; i < codeNo.length; i++) {
map.put(codeNo[i], staVal[i]);
}
final int[] wi = { 3, 7, 9, 10, 5, 8, 4, 2 };
String[] all = orgCode.split("-");
final char[] values = all[0].toCharArray();
int parity = 0;
for (int i = 0; i < values.length; i++) {
final String val = Character.toString(values[i]);
parity += wi[i] * Integer.parseInt(map.get(val).toString());
}
String cheak = (11 - parity % 11) == 10 ? "X" : Integer.toString((11 - parity % 11));
return cheak.equals(all[1]);
}
public static void main(String[] args) {
// 00251807-3 00251808-1
System.out.println(OrgCodeValidation.validate("00251805-7")); // 00251805-7 true
System.out.println(OrgCodeValidation.validate("00251809-X")); // 00251809-X true
}
}