|
14 | 14 | */ |
15 | 15 | public final class Personnummer implements Comparable<Personnummer> { |
16 | 16 | private static final Pattern regexPattern; |
| 17 | + private static final Pattern interimPatternTest; |
| 18 | + private static final String interimTestStr = "(?![-+])\\D"; |
17 | 19 |
|
18 | 20 | static { |
19 | | - regexPattern = Pattern.compile("^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})([-+]?)?((?!000)\\d{3})(\\d?)$"); |
| 21 | + regexPattern = Pattern.compile("^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})([-+]?)?((?!000)\\d{3}|[TRSUWXJKLMN]\\d{2})(\\d?)$"); |
| 22 | + interimPatternTest = Pattern.compile(interimTestStr); |
20 | 23 | } |
21 | 24 |
|
22 | 25 | /** |
@@ -112,6 +115,13 @@ public Personnummer(String personnummer, Options options) throws PersonnummerExc |
112 | 115 | throw new PersonnummerException("Failed to parse personal identity number. Invalid input."); |
113 | 116 | } |
114 | 117 |
|
| 118 | + if (!options.allowInterimNumbers && interimPatternTest.matcher(personnummer).find()) { |
| 119 | + throw new PersonnummerException( |
| 120 | + personnummer + |
| 121 | + " contains non-integer characters and options are set to not allow interim numbers" |
| 122 | + ); |
| 123 | + } |
| 124 | + |
115 | 125 | Matcher matches = regexPattern.matcher(personnummer); |
116 | 126 | if (!matches.find()) { |
117 | 127 | throw new PersonnummerException("Failed to parse personal identity number. Invalid input."); |
@@ -154,9 +164,14 @@ public Personnummer(String personnummer, Options options) throws PersonnummerExc |
154 | 164 |
|
155 | 165 | this.isMale = Integer.parseInt(Character.toString(this.numbers.charAt(2))) % 2 == 1; |
156 | 166 |
|
| 167 | + String nums = matches.group(6); |
| 168 | + if (options.allowInterimNumbers) { |
| 169 | + nums = nums.replaceFirst(interimTestStr, "1"); |
| 170 | + } |
| 171 | + |
157 | 172 | // The format passed to Luhn method is supposed to be YYmmDDNNN |
158 | 173 | // Hence all numbers that are less than 10 (or in last case 100) will have leading 0's added. |
159 | | - if (luhn(String.format("%s%s%s%s", this.year, this.month, this.day, matches.group(6))) != Integer.parseInt(this.controlNumber)) { |
| 174 | + if (luhn(String.format("%s%s%s%s", this.year, this.month, this.day, nums)) != Integer.parseInt(this.controlNumber)) { |
160 | 175 | throw new PersonnummerException("Invalid personal identity number."); |
161 | 176 | } |
162 | 177 | } |
|
0 commit comments