Unicode Regex; Invalid XML characters

I know this isn’t exactly an answer to your question, but it’s helpful to have it here:

Regular Expression to match valid XML Characters:


So to remove invalid chars from XML, you’d do something like

// filters control characters but allows only properly-formed surrogate sequences
private static Regex _invalidXMLChars = new Regex(

/// <summary>
/// removes any unusual unicode characters that can't be encoded into XML
/// </summary>
public static string RemoveInvalidXMLChars(string text)
    if (string.IsNullOrEmpty(text)) return "";
    return _invalidXMLChars.Replace(text, "");

I had our resident regex / XML genius, he of the 4,400+ upvoted post, check this, and he signed off on it.

Leave a Comment