1
Feb

Simple RegEx replace in C#

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; }

There's 1 Comment So Far

Who Linked To This Post?

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

Share your thoughts, leave a comment!