Cheap Web Hosting Providers
C# Programming‎ > ‎

Regular Expressions (Regex)

Regular expressions are used to search/replace expressions in a text, file etc.
There are two parts: 
1. Data in which string to be searched
2. String to be searched in data

Regular expression mainly consists  of

1. literal characters
2. Meta characters

Examples

example string : Once there lived a great king who was very kind and great worrier and greater than any other king of his times.

To search for a word great, regular expression could be just great

But if we have to search for great and greater the regular expression would be great(er)? or greate?r?. Here regular expression consists of literals and metacharacters. ? is a metacharacter which means zero or more existence of character preceding ?

List of metacharacters

 ? Zero or one matches greatt great? will match great
 * Zero or more matches greatt great* will match greatt (greedy)
 + One or more matches great greate+ will not match great            
 {n} exactly n matches greatt great{2} will match greatt not great
 {n,} atleast n matches greattt great{1,} will match greattt (greedy)
 {n,m} atleast n but no more than m matches greattt great{1,2} will match greatt (not greattt)
 ?? no match greatt great?? will match grea 
       
  Zero width assertions  
 ^ Specifies that the match must occur at the beginning of the string or the beginning of the line The stars in the sky.  ^The will match first The    
 $ Specifies that the match must occur at the end of the string, before \n at the end of the string, or at the end of the line. see saw see see$ will match last see
 \b     Specifies that the match must occur on a boundary between \w (alphanumeric) and \W (nonalphanumeric) characters 

Examples:

Once there lived a great king.

^(once)(?: )(th.*)(?: )(liv.*)

will create grouping of matches.
(?: are neglected in group counts)
here groups created are

1. once
2. there
3. lived a great king