Regular expressions

When talking about validating input data, it is important to have an understanding of regular expressions, which is a powerful way to process text. It employs a pattern-matching technique to identify a pattern of text in input texts and validates it to the required format. For example, if our application wants to validate an email, regular expressions can be used to identify whether the email address provided is in a valid format. it checks for .com, @, and other patterns and returns if it matches a required pattern.

System.Text.RegularExpressions.Regex acts as a regular expression engine in .NET Framework. To use this engine, we need to pass two parameters, the first a pattern to match and the second text where this pattern matching happens.

The regex class comes up with four different methods – IsMatch, MatchMatches, and Replace. The IsMatch method is used to identify a pattern in the input text. The Match or Matches methods are used to get all occurrences of text that match a pattern. The Replace method replaces text that matches a regular expression pattern.

Now, let's jump into some examples to understand regular expressions:

public void ReplacePatternText()
{
string pattern = "(FIRSTNAME\.? |LASTNAME\.?)";

string[] names = { "FIRSTNAME. MOHAN", "LASTNAME. KARTHIK" };
foreach(string str in names)
{
Console.WriteLine(Regex.Replace(str, pattern, String.Empty));
}

}

public void MatchPatternText()
{
string pattern = "(Madhav\.?)";

string names = "Srinivas Madhav. and Madhav. Gorthi are same";
MatchCollection matColl = Regex.Matches(names, pattern);
foreach (Match m in matColl)
{
Console.WriteLine(m);
}
}

public void IsMatchPattern()
{
string pattern = @"^cw+";

string str = "this sample is done as part of chapter 11";
string[] items = str.Split(' ');
foreach (string s in items)
{
if (Regex.IsMatch(s, pattern))
{
Console.WriteLine("chapter exists in string str");
}
}
}

The ReplacePatternTest method identifies FirstName and LastName from an array of strings and replaces them with an empty string. In the MatchPatternText method, we identify how many times Madhav exists in the string; in the third method, we use a pattern to identify a chapter word. The ^cw+ pattern represents the beginning of the word, c represents a word starting with c, w represents any characters, and + represents matches with the preceding token. 

The following output shows the first two lines of the output from the ReplacePatternTest method, where we replaced Madhav with an empty string. The second output set identifies a pattern and displays it. The third set is where we identify a chapter word in the string:

//ReplacePatternText method
MOHAN
KARTHIK

//MatchPatternText method
Madhav.
Madhav.

//IsMatchPattern method
chapter exists in string str
Press any key to exit.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.105.159