Search code examples
c#regexdouble-quotessingle-quotes

Regex - Single quotes OR Double quotes -C#


How to change this:

Regex.Match(value, @"href=\""(.*?)\""",RegexOptions.Singleline);

So that it will select href='foobar' (Single quotes ') AS well as selecting href="foobar" (Double quotes ")??


Solution

  • You can use a pattern like this:

    href=(["'])(.*?)\1
    

    This will match any string of that contains href= followed by a " or ' followed by any number of characters (non-greedily) followed by the same character that was matched previously in group 1. Note that \1 is a backreference.

    Also note that this will also mean the contents of your attribute will be captured in group 2 rather than group 1.

    Now, the correct way to escape this string literal would be either like this (using regular strings):

    Regex.Match(value, "href=([\"'])(.*?)\\1", RegexOptions.Singleline);
    

    Or like this (using verbatim strings):

    Regex.Match(value, @"href=([""'])(.*?)\1", RegexOptions.Singleline);