Regular Expression – II

//Matches string start with pattern
String strData = “Hello there”;
Regex rg = new Regex(“^Hello”);
bool truefalse = rg.IsMatch(strData);

rg = new Regex(“^Hola”);
truefalse = rg.IsMatch(strData);

//Matches strung end with pattern
strData = “Hello there”;
rg = new Regex(“there$”);
truefalse = rg.IsMatch(strData);

//Matches char from the list
rg = new Regex(“[aeiou]”);
truefalse = rg.IsMatch(strData);

//Not matches char from the list
rg = new Regex(“[^aeiou]”);
truefalse = rg.IsMatch(strData);

//Matching range
strData = “Hello there, you are 8 years old.”;
rg = new Regex(“[0-9]”);
truefalse = rg.IsMatch(strData);

strData = “55”;
rg = new Regex(“[0-9][0-5]”);
truefalse = rg.IsMatch(strData);

//Match string contains A-Z, a-z and 0-9
strData = “Hello”;
rg = new Regex(“[^a-zA-Z0-9]”);
truefalse = rg.IsMatch(strData);

//Match string contains A-Z, a-z, 0-9 with white space, below code return false when string contains chars other than defined.
strData = “hello there 0″;
rg = new Regex(@”[^a-zA-Z0-9\s]”);
truefalse = rg.IsMatch(strData);

//Matches a-z and A-Z
strData = “hello there”;
rg = new Regex(@”[^\w\s]”);
truefalse = rg.IsMatch(strData);

//Matches a-z, A-Z and 0-9
strData = “hello there 0″;
rg = new Regex(@”[^\w\d\s]”);
truefalse = rg.IsMatch(strData);

//Note*: \w represet a-zA-Z, \W other than word characters and \d represent 0-9, \D other than non-decimal
//\s represent whitespace

//To match the number of characters that matches certain pattern.

//True scenario
strData = “12345”;
rg = new Regex(@”\d{5}”);
truefalse = rg.IsMatch(strData);

strData = “12345-6789″;
rg = new Regex(@”\d{5}-\d{4}”);
truefalse = rg.IsMatch(strData);

//False scenario
strData = “12345-678″;
rg = new Regex(@”\d{5}-\d{4}”);
truefalse = rg.IsMatch(strData);

strData = “12345-678A”;
rg = new Regex(@”\d{5}-\d{4}”);
truefalse = rg.IsMatch(strData);

//Minimum and Maximum Occurences
//True scenario
strData = “123”;
rg = new Regex(@”\d{1,3}”);
truefalse = rg.IsMatch(strData);

strData = “12”;
rg = new Regex(@”\d{1,3}”);
truefalse = rg.IsMatch(strData);

//False scenario – string end with numeric
strData = “A124B”;
rg = new Regex(@”\d{1,3}$”);
truefalse = rg.IsMatch(strData);

#regular-expression

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s