sample code to find all words that start with letter "M"
privatestaticvoidMain(){// Create a pattern for a word that starts with letter "M"stringpattern=@"\b[M]\w+";// Create a RegexRegexrg=newRegex(pattern);// Long stringstringauthors="Mahesh Chand, Raj Kumar, Mike Gold, Allen O'Neill, Marshal Troll";// Get all matchesMatchCollectionmatchedAuthors=rg.Matches(authors);// Print all matched authorsfor(inti=0;i<matchedAuthors.Count;i++){Console.WriteLine(matchedAuthors[i].Value);}Console.ReadLine();}
staticvoidMain(string[]args){stringstr="A Thousand Splendid Suns";Console.WriteLine("Matching words that start with 'S': ");showMatch(str,@"\bS\S*");Console.ReadKey();}
Matching words that start with 'S':
The Expression: \bS\S*
Splendid
Suns
staticvoidMain(string[]args){stringstr="make maze and manage to measure it";Console.WriteLine("Matching words start with 'm' and ends with 'e':");showMatch(str,@"\bm\S*e\b");Console.ReadKey();}
Matching words start with 'm' and ends with 'e':
The Expression: \bm\S*e\b
make
maze
manage
measure
usingSystem;usingSystem.Text.RegularExpressions;namespaceRegExApplication{classProgram{staticvoidMain(string[]args){stringinput="Hello World ";stringpattern="\\s+";stringreplacement=" ";Regexrgx=newRegex(pattern);stringresult=rgx.Replace(input,replacement);Console.WriteLine("Original String: {0}",input);Console.WriteLine("Replacement String: {0}",result);Console.ReadKey();}}}
Original String: Hello World
Replacement String: Hello World
Code Check if string is valid prefix for file name
string[]prefixs={"M1","1","-","M1-"," ","M1_M2","M1_"};foreach(stringprefixinprefixs){//\W check if string contain any non word character//|is used to combine two checks//_$ check if string end with Underscorevarmatch=Regex.IsMatch(prefix,@"\W|_$");Console.WriteLine(prefix+" is "+(match?"InValid":"Valid"));}
publicstaticclassCoordinateDataValidation{publicstaticboolIsValid(stringdata){//Must Only Contain one commaif(Regex.Matches(data,",{1}").Count!=1){returnfalse;}//Must not contain any symbol except commaif(Regex.Matches(data,@"[^\d,-]").Count>0){returnfalse;}if(Regex.Matches(data,@"[\d-][\d]*,[\d-][\d]*").Count!=1){returnfalse;}returntrue;}}