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
Example: Input values contains alpha numeric but it
may contains special character ‘%’ on first position but occurrence will be 1
or 0:
2. Exact Matches:
Example: Input values contains alpha numeric but length
should be 4
3 . Matches
between ranges
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
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
a{5} - exactly five length
a{2} - exactly two length
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
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:
Post a Comment