RegEx for validating CNIC numbers of Pakistan
CNIC
stands for Computerized National Identiry Card
. There are two ways we can actually write CNIC numbers:
12345-1234567-1
1234512345671
One with dashes and one without dashes but not mixed with other.
^([0-9]{5})-([0-9]{7})-([0-9]{1})$
Example: 12345-1234567-1
^([0-9]{5})([0-9]{7})([0-9]{1})$
Example: 1234512345671
^(([\d]{5})-([\d]{7})-([\d]{1}))|(([\d]{5})([\d]{7})([\d]{1}))|(([\d]{5}) ([\d]{7}) ([\d]{1}))$
This is a mixture of three different regex.
Test it online on RegExr or regex101
Above Final regex will allow the following CNIC patterns and will reject all others
1234512345671
12345-1234567-1
12345 1234567-1
12345-1234567 1
12345123456718
12345-1234567-71
12345-12345678-1
...
The last digit says gender of citizen. You can extract gender entity only by checking for last value. If it is Even Number
its female, while Odd Number
is used for Male
, You can do it only if your users alowed this, you can only know someone gender if only they want you to know.
Code generated by regex101.com
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^(([\\d]{5})-([\\d]{7})-([\\d]{1}))|(([\\d]{5})([\\d]{7})([\\d]{1}))|(([\\d]{5}) ([\\d]{7}) ([\\d]{1}))$";
final String string = "// Allow these: \n"
+ "1234512345671\n"
+ "12345-1234567-1\n\n"
+ "// Don't Allow\n"
+ "12345 1234567-1\n"
+ "12345-1234567 1\n"
+ "12345123456718\n"
+ "12345-1234567-71\n"
+ "12345-12345678-1\n\n";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
By compiling code online via online compiler we got following output:
$javac Example.java
$java -Xmx128M -Xms16M Example
Full match: 1234512345671
Group 1: null
Group 2: null
Group 3: null
Group 4: null
Group 5: 1234512345671
Group 6: 12345
Group 7: 1234567
Group 8: 1
Group 9: null
Group 10: null
Group 11: null
Group 12: null
Full match: 12345-1234567-1
Group 1: 12345-1234567-1
Group 2: 12345
Group 3: 1234567
Group 4: 1
Group 5: null
Group 6: null
Group 7: null
Group 8: null
Group 9: null
Group 10: null
Group 11: null
Group 12: null
Full match: 1234512345671
Group 1: null
Group 2: null
Group 3: null
Group 4: null
Group 5: 1234512345671
Group 6: 12345
Group 7: 1234567
Group 8: 1
Group 9: null
Group 10: null
Group 11: null
Group 12: null
Full match: 12345-1234567-7
Group 1: 12345-1234567-7
Group 2: 12345
Group 3: 1234567
Group 4: 7
Group 5: null
Group 6: null
Group 7: null
Group 8: null
Group 9: null
Group 10: null
Group 11: null
Group 12: null