Simple RegEx replace in C#

February 1st, 2007

As I don’t use regular expressions that often I always forget the syntax. So I thought I just put a basic replace pattern up here.

This method takes a schema, finds all places where is says schemaLocation=”whatever” in a text and changes this to schemaLocation=”whatever.xsd and then returns the schema.

private XmlSchema FixSchemaLocation(XmlSchema schema) { System.Text.RegularExpressions.Regex locationReplacePattern = new System.Text.RegularExpressions.Regex("schemaLocation=\"(?<location>.*?)\""); string locationReplaceValue = "schemaLocation=\"${location}.xsd\""; //Puts .xsd after the schemaLocation. We need this find the imported schemas StringWriter sw = new StringWriter(); schema.Write(sw); XmlSchema formatedSchema = XmlSchema.Read(new StringReader(locationReplacePattern.Replace(sw.ToString(), locationReplaceValue)),null); return formatedSchema; }

One Response to “Simple RegEx replace in C#”

  1. プログラマー's 雑録 Says:

    メール形式のチェック…

    using System.Text.RegularExpressions; Regex reg = new Regex(@&#38;quot;^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$&#38;quot;); if(reg.IsMatch(&#38;quot;mail address&#38;quot;)) { &#38;…

Leave a Reply