Regular Expression Examples

2012-07-11

1. Requirement:

a) Match all the airline codes, comma can be considered if more than one airline code is coming in the input.

b) Airline code should be alphanumeric.

c) Airline code length should be b/w 2 to 3.

d) No other characters except alphanumeric should not be matched for airline code.

Valid Inputs:

1. SG

2. 6E,G8

3. 34,RG,WPI

4. 12

5. 123

Invalid Inputs:

1.ABCD

2.AB,

3.1234

4.AB,DF'

Solution:

1
[a-z0-9] {2,3}
- This will match our airline code which contains only alpha numeric.

Now as per requirement it's allowed that more than 1 airline code can be accepted. So we have to accept comma(i.e ,) symbol

also. If comma symbol comes then it should be succeded by airline code pattern otherwise the input becomes invalid as like in

the example 2 shown in "Invalid Examples:".

So the (comma+airline code)pattern should come together always after the first airline code.

Also (comma+airline code)pattern may repeat 1 or more times or 0 times.

i.e (comma+airline code)*

i.e

1
([,][a-z0-9]{2,3})*


Now the full pattern:


1
[a-z0-9]{2,3} ([,][a-z0-9]{2,3})*


Now we want to match the input with the pattern exactly from the beginning of the input character to the last character, not just match in the entire input. Other wise it will match characters in the string which has got alphanumeric characters or comma .To avoid this we have to use ^ and $.


i.e final expression

1
^[a-z0-9]{2,3}([,][a-z0-9]{2,3})*$

Sample working code:

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
 
namespace Tool
{
     
    class Program
    {
        private static string AirlineCodeExpression = "^[a-z0-9]{2,3}([,][a-z0-9]{2,3})*$";
        private static string inputStringToMatchPatten = string.Empty;
        static void Main(string[] args)
        {
            while (true)
            {
                Regex pattern = new Regex(AirlineCodeExpression, RegexOptions.IgnoreCase);
                Console.WriteLine("Enter the string");
                inputStringToMatchPatten = Console.ReadLine();
                if (pattern.IsMatch(inputStringToMatchPatten))
                {
                    Console.WriteLine("Success");
                }
                else
                {
                    Console.WriteLine("Failed");
                }
            }                       
        }
    }
}

0 comments: