Regular Expressions – validating the NIC number

Regular expressions!!! kind of a scary thing for most developers.. 🙂 Well it is scary because its not something that is really user friendly for developers, its a combination of letters, special characters and numbers that kind of make our eyes go the wrong way when we look at them.

Well I normally don’t like to use regular expressions, I just copy from some web site and paste the regular expression when I really need to use one. But I needed to learn how to build my own regular expression and I couldn’t find one on the Internet. What a bummer that was 🙂

What I wanted to do was to validate a National Identity Card (NIC) number (Sri Lankan). Which is 9 number followed by one letter that is v, V, x or X.

So how to write the regular expression for this?

Well you start with


that means that the regular expression is started.

Now we need to tell them that next nine characters should be numbers,


that is how you say numbers 🙂 , how to tell them that next 9 digits are numbers???


the number in curly brackets is the number of times to repeat.

Next we need to tell the regular expression that next letter should be x, X, v or V.


and then we need to tell that the regular expression is over. you do that by,


The final version of the regular expression for validating the NIC number is,


It is really easy when you break it down like that. 😀


17 thoughts on “Regular Expressions – validating the NIC number

  1. ishan

    didnt work with mine 😦 im working on c#. so if i do like below that should work or am i doing i wrong?

    if (Regex.IsMatch(someTextBox.Text, @”/^[0-9]{9}[vVxX]$/”))
    do something;

    1. surendias Post author

      Hi Ishan,

      I used this with java. I’m not really sure how to use it in C#. If the syntax is correct for the string matching then the regular expression should be the same.

  2. choolani abegunawardhana

    please explain me how to use above expression in Javascript. can we use like below,
    var RegExp= ^/[0-9]{9}[vVxX]$/
    alert(“Please enter a valid id number”);
    return false;


Let me know what you think .. :)

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s