Alvin’s Blog

June 25, 2009

RegEx: Match word boundaries

Filed under: RegEx — amcbride @ 6:11 pm

// matches “forfeiture” or “52″

System.Text.RegularExpressions.Regex rg = new Regex(@”\bforfeiture\b|\b52\b”, RegexOptions.IgnoreCase);

Match m = rg.Match(“forfeiture 52 dkjf 520 foooj”);

while (m.Success)
{
string s = m.ToString();
m = m.NextMatch();
}

March 9, 2009

RegEx: Replace string within a file

Filed under: .NET, RegEx — amcbride @ 11:43 pm

Sample Call

ReplaceInFile(@”x:\setup\P8574.T857402.R45.T107801.CSV”, @”\s{65,}”, System.Environment.NewLine);

 
/// <summary>
/// Replaces text in a file.
/// </summary>
/// <param name=”filePath”>Path of the text file.</param>
/// <param name=”searchText”>Text to search for.</param>
/// <param name=”replaceText”>Text to replace the search text.</param>
static public void ReplaceInFile( string filePath, string searchText, string replaceText )
{
 StreamReader reader = new StreamReader( filePath );
        string content = reader.ReadToEnd();
        reader.Close();

        content = Regex.Replace( content, searchText, replaceText, RegexOptions.Singleline);

        StreamWriter writer = new StreamWriter( filePath );
        writer.Write( content );
        writer.Close();
}

Blog at WordPress.com.