How to find specific charcter pattern in large amount of Text

TO find specific pattern in larger amount of text we will use Regex class. The following example demonstrate how to use regex class


Step :-1 Create the objects


StreamReader sr = new StreamReader(filename);
string input;
string pattern = @"\b(\w+)\s\1\b";




Step 2:- It reads from string reader until last


while (sr.Peek() >= 0)
{
input = sr.ReadLine();



Step 3:- Creates the new Regex object it takes two parameter, first is the pattern and secode is enumeration specifying to ignore the case


Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);


Step 4:- Matches method of regex class' object find the number of occurence in the specified input string


MatchCollection matches = rgx.Matches(input);



Step 5:- To print the occurence if it finds anyone



if (matches.Count > 0)
{
Console.WriteLine("{0} ({1} matches):", input, matches.Count);
foreach (Match match in matches)
Console.WriteLine(" " + match.Value);
}


Step 6:- finally close the string reader object



}
sr.Close();


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: