Monday, April 1, 2019

Regular Expression Quantifiers in *, +, ?, {, and } characters

This blog will demonstrates how to write the regular expression for matching occurrence like 0 or more, 1 or more or 0 or 1 or exact number matches or range matches

1.       Occurrence matches ( 0 or more, 1 or more or 0 or 1)

a*           -  0 or more
a+           -  1 or more
a?           -  0 or 1

 Example:  Input values contains alpha numeric but it may contains special character ‘%’ on first position but occurrence will be 1 or 0:
1
2
3
4
string regExpression = @"^[%]?[a-zA-Z0-9]*$";
string input = "%Rajeev12";
Console.WriteLine(Regex.IsMatch(input, regExpression));
Console.ReadKey();

Console Output:  True
1
2
3
4
string regExpression = @"^[%]?[a-zA-Z0-9]*$";
string input = "Rajeev123";
Console.WriteLine(Regex.IsMatch(input, regExpression));
Console.ReadKey();

Console Output:  True

In this scenario, input value have more than 1 special character ‘%'
1
2
3
4
string regExpression = @"^[%]?[a-zA-Z0-9]*$";
string input = "%%Rajeev123";
Console.WriteLine(Regex.IsMatch(input, regExpression));
Console.ReadKey();

 Console Output:  False

 2.        Exact Matches:

a{5}  - exactly five length
a{2} - exactly two length

 Example:  Input values contains alpha numeric but length should be 4

1
2
3
4
string regExpression = @"^[a-zA-Z0-9]{4}$";
string input = "123b";     
Console.WriteLine(Regex.IsMatch(input, regExpression));
Console.ReadKey();

Console Output:  True

string regExpression = @"^[a-zA-Z0-9]{4}$";
string input = "1234b";        
Console.WriteLine(Regex.IsMatch(input, regExpression));
Console.ReadKey();


Console Output:  False

 3.       Matches between ranges

              a{1,3}    between one & three

Example:  Input values contains alpha numeric but length should be between 1 and 3

1
2
3
4
string regExpression = @"^[a-zA-Z0-9]{1,3}$";
string input = "123b";
Console.WriteLine(Regex.IsMatch(input, regExpression));
Console.ReadKey();

Console Output:  False
1
2
3
4
string regExpression = @"^[a-zA-Z0-9]{1,3}$";
string input = "123";
Console.WriteLine(Regex.IsMatch(input, regExpression));
Console.ReadKey();

Console Output:  True
1
2
3
4
string regExpression = @"^[a-zA-Z0-9]{1,3}$";
string input = "23";
Console.WriteLine(Regex.IsMatch(input, regExpression));
Console.ReadKey();

Console Output:  True

No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...