-1

I have the following code:

public string LoadTemplate()
{
    return "<!-- *style -->\r\n<style>\r\n    .page {\r\n        display: grid;\r\n        grid-template-columns: repeat(3, 1fr);\r\n        grid-template-rows: repeat(7, 13.468%);\r\n        align-content: end;\r\n        width: var(--w);\r\n        aspect-ratio: 210 / 297; /* A4 portrait */\r\n    }\r\n</style>\r\n<!-- /style -->\r\n<div class=\"page\" style=\"[style]\">\r\n[items]\r\n</div>";
}
private static Regex _styleRegex = new Regex(@"<!-- \*style -->(.+)<!-- \/style -->", RegexOptions.Multiline);
public string Style
{
    get
    {
        var match = _styleRegex.Match(LoadTemplate());
        if (match.Success)
        {
            return match.Groups[1].Value;
        }
        return null;
    }
}

(The original of LoadTemplate does a lot more. For short I just made it return a sample template here.) When getting Style, I get null.

I was hoping to get the style section, but without the html comments around it.

I used several online Regex Testers to see if I could find what the problem was. All indicate there should be a match, and group 1 should hold the style section of the source string.

I traced Style-get. And match.Success is always false.

How do I find out what the problem is?

InSync
  • 4,851
  • 4
  • 8
  • 30

1 Answers1

1

You just have to enable Dot-all mode (?s) so the dot will match newlines.
And spans lines.

@"(?s)<!--\s*\*\s*style\s*-->(.+?)<!--\s*/style\s*-->"

https://regex101.com/r/JuYFsB/1

(?s)
<!-- \s* \* \s* style \s* -->
( .+? )                       # (1)
<!-- \s* /style \s* -->

And adding optional white space makes it more flexible.

sln
  • 2,071
  • 1
  • 3
  • 11