Sukumar Raju's Blog

MCP

Sponsors

Tags

News

SharePoint SharePoint

More reading these days Patterns and practicces


Interesting to work with ASP.NET Membership provider

Suggested Reading C# Book


patterns & practices Application Architecture Guide 2.0


MVP Blog Badge.

Grab this badge here!


Extract Year and Text between brackets using Regular Expressions

Hi All,

It is straight forward to use Regular expressions to extract text from a string. Below code snippet demos extracting year from a string and Text in between brackets from a string.

Extract Text between brackets

   1: static void Main(string[] args)
   2:         {
   3:             
   4:             //Regular Expression pattern 
   5:             string Pattern = @"\((.*?)\)";
   6:             //Regular Expression with pattern
   7:             Regex re = new Regex(Pattern);
   8:             string strSearch = "Microsoft (www.msdn.com)";
   9:  
  10:             //Loop through the string and output the matching text
  11:             foreach(Match m in re.Matches(strSearch))
  12:             {
  13:              Console.Write(m.Value.Replace("(",string.Empty).Replace(")",string.Empty).Trim());
  14:                 
  15:             }
  16:             Console.ReadKey();
  17:         }

Extract Year from string

   1: //Regular expression for year
   2: string pattern = "([0-9]{4})";
   3: Regex re = new Regex(pattern);
   4: string txtYear = string.Empty;
   5:  
   6: string strSearch = "SharePoint 2010";
   7:  
   8: foreach (Match m in re.Matches(strSearch))
   9: {
  10:     txtYear = m.Value;
  11:     Console.Write(txtYear);
  12: }   
  13:  
  14: Console.ReadKey();
  15:         }

References

http://support.microsoft.com/kb/308252

http://msdn.microsoft.com/en-us/library/ms228595(v=VS.80).aspx

http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet

Comments

No Comments

Leave a Comment

(required) 

(required) 

(optional)

(required)