C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

Regular expression for matching text between specific delimiters


Posted Date: 03 Mar 2004    Resource Type: Articles    Category: .NET Framework
Author: Tony JohnMember Level: Diamond    
Rating: 1 out of 5Points: 10



Regular expressions are very helpful in finding patterns in text. C# and .Net supports regular expressions by a set of classes in the namespace System.Text.RegularExpressions. Instead of looping through the entire text and doing text comparison, regular expressions can do this job real fast.

The following samples demonstrate usage of regular expressions in C#

Regular expression sample to match text between specific characters.
This sample displays all text between square brackets - [ and ]


string text = "Hello [JOHN], how are you and [TIMS] ? Did you meet [BILL] this week ?";

// Square brackets - [ ] are special characters in regular expression. So, they have to
// be 'escaped' with a backslash. But backslash itself is a special character
// in C# and so need to be use the escape character. So
// we are using \\[ just to represent the [ and \\] to represent ].

string exp = "\\[(.*?)\\]";

Regex reg = new Regex( exp );

MatchCollection matches = Regex.Matches(text, exp, RegexOptions.IgnoreCase );
IEnumerator en = matches.GetEnumerator();

while ( en.MoveNext() )
{
Match match = (Match) en.Current;
MessageBox.Show( match.Value );
}


This sample displays all text between angle brackets - < and >.


string text = "Hello <JOHN>, how are you and <TIMS> ? Did you meet <BILL> this week ?";

string exp = "<(.*?)>";

Regex reg = new Regex( exp );

MatchCollection matches = Regex.Matches(text, exp, RegexOptions.IgnoreCase );
IEnumerator en = matches.GetEnumerator();

while ( en.MoveNext() )
{
Match match = (Match) en.Current;
MessageBox.Show( match.Value );
}




Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Arrays in VB.NET
Previous Resource: Regular expression to count number of words
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
Related Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use