Thursday, 14 June 2012

C# Regex replace

[Test]
public void TestRegexReplace()
{
  //replace A or B with X after \Date\
  var pattern = @"\b(?<=\\Date\\)(A|B)\b";
  
  Assert.AreEqual(
	@"c:\temp\Date\X\SubFolder\",
	Regex.Replace(@"c:\temp\Date\A\SubFolder\", pattern, m => "X"));
  
  Assert.AreEqual(
	@"c:\temp\Date\X\SubFolder\",
	Regex.Replace(@"c:\temp\Date\B\SubFolder\", pattern, m => "X"));
  
  Assert.AreEqual(
	@"c:\temp\Date\C\SubFolder\", Regex.Replace(
	@"c:\temp\Date\C\SubFolder\", pattern, m => "X"));
  
  //or the simple way :)
  
  pattern = @"\\Date\\[AB]\\";
  
  Assert.AreEqual(
	@"c:\temp\Date\X\SubFolder\",
	Regex.Replace(@"c:\temp\Date\A\SubFolder\", pattern, m => @"\Date\X\"));
  
  Assert.AreEqual(
	@"c:\temp\Date\X\SubFolder\",
	Regex.Replace(@"c:\temp\Date\B\SubFolder\", pattern, m => @"\Date\X\"));
  
  Assert.AreEqual(
	@"c:\temp\Date\C\SubFolder\", Regex.Replace(
	@"c:\temp\Date\C\SubFolder\", pattern, m => @"\Date\X\"));
}

No comments:

Post a Comment