Best Industrial Training in C,C++,PHP,Dot Net,Java in Jalandhar

Thursday, 24 August 2017

Regular Expressions (RegEx) in ASP.NET

Regex has been the most popular and easiest way of writing validations. The only big problem with regex has been the cryptic syntax. Developers who are working on projects with complicated validation always refer some kind of cheat sheet to remember the syntaxes and commands.
In this article we will try to understand what regex is and how to remember those cryptic syntaxes easily.
FYI :- This article will use c# language to demonstrate regex implementation , so in case you are using other languages , syntaxes can change accordingly. 
You can watch my .NET interview questions and answers videos on various sections like WCF, SilverLight, LINQ, WPF, Design patterns, Entity framework etc.

Just in case if you are new comer, what is regex?

Regex or regular expression helps us describe complex patterns in texts. Once you have described these patterns you can use them to do searching, replacing, extracting and modifying text data.

Below is a simple sample of regex. The first step is to import the namespace for regular expressions.
using System.Text.RegularExpressions;
The next thing is to create the regex object with the pattern. The below pattern specifies to search for alphabets between a-z with 10 length.
Regex obj = new Regex("[a-z]{10}");
Finally search the pattern over the data to see if there are matches. In case the pattern is matching the ‘IsMatch’ will return true.
MessageBox.Show(obj.IsMatch("shivkoirala").ToString());

3 important regex commands

The best way to remember regex syntax is by remembering three things Bracket, caret and Dollars.
B
There are 3 types of brackets used in regular expression
Square brackets “[“and Curly “{“ brackets.
Square brackets specify the character which needs to be matched while curly brackets specify how many characters. “(“ for grouping.
We will understand the same as we move ahead in this article.
Ccaret “^” marks the start of a pattern.^ may appear at the beginning of a pattern to require the match to occur at the very beginning of a line. For example, ^xyz matches xyz123 but not 123xyz. 
DDollar “$” marks the end of a pattern.$ may appear at the end of a pattern to require the match to occur at the very end of a line. For example, pqr$ matches 123pqr but not pqr123. 
Caret (^) and dollar sign ($) indicate the pattern to the beginning or end of the string being searched.The two anchors may be combined. For example, ^pqr$ matches only pqr. Any characters after or before it will make the pattern invalid.  
Now once you know the above three syntaxes you are ready to write any validation in the world. For instance the below validation shows how the above three entities fit together.  
 
  • The above regex pattern will only take characters which lies between ‘a’ to ‘z’. The same is marked with square bracket to define the range.
  • The curly bracket's indicates the minimum and maximum length.
  • Finally caret sign at the start of regex pattern and dollar at the end of regex pattern specifies the start and end of the pattern to make the validation more rigid.
So now using the above 3 commands let’s implement some regex validation.


Check if the user has entered shivkoirala?

shivkoirala

Let’s start with the first validation, enter character which exists between a-g?

[a-g]

Enter characters between [a-g] with length of 3?

[a-g]{3}

Enter characters between [a-g] with maximum 3 characters and minimum 1 character?

[a-g]{1,3}

How can I validate data with 8 digit fix numeric format like 91230456, 01237648 etc?

^[0-9]{8}$

How to validate numeric data with minimum length of 3 and maximum of 7, ex -123, 1274667, 87654?

We need to just tweak the first validation with adding a comma and defining the minimum and maximum length inside curly brackets.
^[0-9]{3,7}$


Validate invoice numbers which have formats like LJI1020, the first 3 characters are alphabets and remaining is 8 length number?

First 3 character validation
^[a-z]{3}
8 length number validation
[0-9]{8}

Now butting the whole thing together.
^[a-z]{3}[0-9]{7}$


Check for format INV190203 or inv820830, with first 3 characters alphabets case insensitive and remaining 8 length numeric?

In the previous question the regex validator will only validate first 3 characters of the invoice number if it is in small letters. If you put capital letters it will show as invalid. To ensure that the first 3 letters are case insensitive we need to use ^[a-zA-Z]{3} for character validation.
Below is how the complete regex validation looks like.
^[a-zA-Z]{3}[0-9]{7}$


Can we see a simple validation for website URL’s?

StepsRegex
Step 1 :- Check is www exist
^www.
Step 2 :-The domain name should be atleast 1 character and maximum character will be 15.
. [a-z]{1,15}
Step 3 :-Finally should end with .com or .org
. (com|org)$
^www[.][a-z]{1,15}[.](com|org)$

Let’s see if your BCD works for email validation?

StepsRegex
Step 1 :- Email can start with alphanumeric with minimum 1 character and maximum 10 character. , followed by at the rate (@)
^[a-zA-Z0-9]{1,10}@
Step 2 :-The domain name after the @ can be alphanumeric with minimum 1 character and maximum 10 character , followed by a “.”
[a-zA-Z]{1,10}.
Step 3 :-Finally should end with .com or .org
.(com|org)$
^[a-zA-Z0-9]{1,10}@[a-zA-Z]{1,10}.(com|org)$

Validate numbers are between 0 to 25

^(([0-9])|([0-1][0-9])|([0-2][0-5]))$

Validate a date with MM/DD/YYYY, YYYY/MM/DD and DD/MM/YYYY

Steps
Regex
Description
Let check for DD. First DD has a range of 1-29 ( feb) , 1-30 (small months) , 1-31 (long month) .
So for DD 1-9 or 01-09
[1-9]|0[1-9]
This allow user to enter value between 1 to 9 or 01 to 09.
Now also adding DD check of 10 to 19
[1-9]|1[0-9]
This allows user to enter the value between 01 to 19.
Now adding to above DD check of 20 to 29
[1-9]|1[0-9]|2[0-9]
This allows user to enter the value between 01 to 29.
Now adding to above DD check of 30 to 31
[1-9]|1[0-9]|2[0-9]|3[0-1]
Finally user can enter value between 01 to 31.
Now for seperator it can be a / , -
[/ . -]
This allows user to seperate date by defining seperator.
Now same applying for MM
[1-9]|0[1-9]|1[0-2]
This allow user to enter month value between 01 to 12.
Then for a YY
1[9][0-9][0-9]|2[0][0-9][0-9]
allow user enter the year value between 1900 to 2099.
^([1-9]|0[1-9]|1[0-2])[- / .]([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])[- / .](1[9][0-9][0-9]|2[0][0-9][0-9])$
And finally to get YYYY/MM/DD use the following regex pattern.
^(1[9][0-9][0-9]|2[0][0-9][0-9])[- / .]([1-9]|0[1-9]|1[0-2])[- / .]([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])$

Short cuts

You can also use the below common shortcut commands to shorten your regex validation.
Actual commandsShortcuts
[0-9]\d
[a-z][0-9][_]\w
O or more occurrences*
1 or more occurrences+
0 or 1 occurrence?

Sunday, 22 March 2015

Login Program in C?

#include<conio.h>
#include<stdio.h>
#include<string.h>
void main()
{
   char userid[]="admin",password[]="123",p[15],u[15];
   int n=1,a,b;
   printf("\nEnter USER ID and PASSWORD below (You have only three chances to enter)");
   getch();
   while(n<=3)
   {
      clrscr();
      printf("\nUSER ID: ");
      scanf("%s",u);
      printf("\nPASSWORD: ");
      scanf("%s",p);
      a=strcmp(u,userid);
      b=strcmp(p,password);
      if(a==0&&b==0)
      {
         printf("\nYou have logged in successfully.");
         break;
      }
      else
      {
         printf("\nWrong PASSWORD and/or USER ID. Now you have % d more chance/s.",3-n);
      }
      getch();
      n++;
   }
   if(n==4)
      printf("\nYou can't log in.");
   getch();
}

Wednesday, 25 February 2015

Call by Value and Call by Reference

Passing Argument to Function :

  1. In C Programming we have different ways of parameter passing schemes such as Call by Value and Call by Reference.
  2. Function is good programming style in which we can write reusable code that can be called whenever require.
  3. Whenever we call a function then sequence of executable statements gets executed. We can pass some of the information to the function for processing calledargument.

Two Ways of Passing Argument to Function in C Language :

  1. Call by Reference
  2. Call by Value
Let us discuss different ways one by one –

A.Call by Value :

#include<stdio.h>

void interchange(int number1,int number2)
{
    int temp;
    temp = number1;
    number1 = number2;
    number2 = temp;
}

int main() {

    int num1=50,num2=70;
    interchange(num1,num2);

    printf("\nNumber 1 : %d",num1);
    printf("\nNumber 2 : %d",num2);

    return(0);
}

Output :

Number 1 : 50
Number 2 : 70

Explanation : Call by Value

  1. While Passing Parameters using call by value , xerox copy of original parameter is created and passed to the called function.
  2. Any update made inside method will not affect the original value of variable in calling function.
  3. In the above example num1 and num2 are the original values and xerox copy of these values is passed to the function and these values are copied into number1,number2 variable of sum function respectively.
  4. As their scope is limited to only function so they cannot alter the values inside main function.
Call by Value in C Programming Scheme

B.Call by Reference/Pointer/Address :

#include<stdio.h>

void interchange(int *num1,int *num2)
{
    int temp;
    temp  = *num1;
    *num1 = *num2;
    *num2 = temp;
}

int main() {

    int num1=50,num2=70;
    interchange(&num1,&num2);

    printf("\nNumber 1 : %d",num1);
    printf("\nNumber 2 : %d",num2);

    return(0);
}

Output :

Number 1 : 70
Number 2 : 50

Explanation : Call by Address

  1. While passing parameter using call by address scheme , we are passing the actual address of the variable to the called function.
  2. Any updates made inside the called function will modify the original copy since we are directly modifying the content of the exact memory location.
Call by Pointer or Address or Reference in C Programming Scheme

Summary of Call By Value and Call By Reference :

PointCall by ValueCall by Reference
CopyDuplicate Copy of Original Parameter is PassedActual Copy of Original Parameter is Passed
ModificationNo effect on Original Parameter after modifying parameter in functionOriginal Parameter gets affected if value of parameter changed inside function

Wednesday, 28 January 2015

MCQ on C

What is the output of this C code?
  1.     #include <stdio.h>
  2.     int main()
  3.     {
  4.         int i = 0;
  5.         int x = i++, y = ++i;
  6.         printf("%d % d\n", x, y);
  7.         return 0;
  8.     }
a) 0, 2
b) 0, 1
c) 1, 2
d) Undefined

What is the output of this C code?
  1.     #include <stdio.h>
  2.     void main()
  3.     {
  4.         int x = 97;
  5.         int y = sizeof(x++);
  6.         printf("X is %d", x);
  7.     }
a) X is 97
b) X is 98
c) X is 99
d) Run time error

What is the output of this C code?
  1.     #include <stdio.h>
  2.     void main()
  3.     {
  4.         int x = 4, y, z;
  5.         y = --x;
  6.         z = x--;
  7.         printf("%d%d%d", x,  y, z);
  8.     }
a) 3 2 3
b) 2 3 3
c) 3 2 2
d) 2 3 4

What is the output of this C code?
  1.  #include <stdio.h>
  2.     void main()
  3.     {
  4.         int a = 5, b = -7, c = 0, d;
  5.         d = ++a && ++b || ++c;
  6.         printf("\n%d%d%d%d", a,  b, c, d);
  7.     }
a) 6 -6 0 0
b) 6 -5 0 1

c) -6 -6 0 1
d) 6 -6 0 1


. What is the output of this C code?
  1.  #include <stdio.h>
  2.     void main()
  3.     {
  4.         int a = -5;
  5.         int k = (a++, ++a);
  6.         printf("%d\n", k);
  7.     }
a) -4
b) -5
c) 4
d) -3

 What is the difference between the following 2 codes?
  1.     #include <stdio.h> //Program 1
  2.     int main()
  3.     {
  4.         int d, a = 1, b = 2;
  5.         d =  a++ + ++b;
  6.         printf("%d %d %d", d, a, b);
  7.     }
  1.     #include <stdio.h> //Program 2
  2.     int main()
  3.     {
  4.         int d, a = 1, b = 2;
  5.         d =  a++ +++b;
  6.         printf("%d %d %d", d, a, b);
  7.     }
a) No difference as space doesn’t make any difference, values of a, b, d are same in both the case
b) Space does make a difference, values of a, b, d are different
c) Program 1 has syntax error, program 2 is not
d) Program 2 has syntax error, program 1 is not



What is the output of this C code?
  1.     #include <stdio.h>
  2.     int main()
  3.     {
  4.         int a = 1, b = 1, c;
  5.         c = a++ + b;
  6.         printf("%d, %d", a, b);
  7.     }
a) a = 1, b = 1
b) a = 2, b = 1
c) a = 1, b = 2
d) a = 2, b = 2