Simple RegEx replace in C#
Thursday, February 1st, 2007As 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; }