C#: Parsing a string using Regular Expressions (Regex)

Using the same root Pattern “(.*?)” to achieve different tasks.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace simpleReg
class Program
static void Main(string[] args)
string practice = “AAMaAAAnAAtasAAACAodAAe”;
//Remove “A” from practice string

//Regular Expressions are great for string manipulation
string path = “C:\\folderParent\\Folder\\fileName.xox”;
Console.WriteLine(“directory String : “+path);

//get filename and extention from full path by using Regex.Replace
//Grab everything before the last “\” and replace it with “”
Console.WriteLine(“filename + extention: “+Regex.Replace(path,”(.*?)\\\\”,””).ToString());

//get file extention from full path using Regex.Match()
//Grab everything after the “.”
Console.WriteLine(“extention only : “+ Regex.Match(path, @”\.(.*)”).ToString());

//parse pattern between two string fragments
string longStr=@”it’s like watching a paper dog chase an asbestos cat through hell.”;
//match between “watching” and “chase”
Console.WriteLine(@”watching ? chase : “+ Regex.Match(longStr,”watching(.*?)chase”).ToString());

//match between “an” and “cat
Console.WriteLine(“an ? cat : “+ Regex.Match(longStr, “an(.*?)cat”).ToString());

//parse pattern between two repeating string fragments
string longerStr = @”it’s like watching a
paper dog chase an asbestos cat through hell.”;
//create Regex pattern
Regex regPattern = new Regex(@”(.*?)”,RegexOptions.Singleline);
//create MatchCollection and populate it with your matches
MatchCollection matchX = regPattern.Matches(longerStr);
//loop through matches
Console.WriteLine(“MatchCollection Matches ;”);
foreach (Match match in matchX)

Leave a Reply

Your email address will not be published.