Search code examples
c#regexasp.net-mvc-validation

Match regex that doesn't contain pair of tags


I build form to create custom WebForms master pages. I need to validate with regular expression if custom text, that will be placed inside master page, does not contain <% and %> tags and any text between them. Input can have multiple lines.

Valid input:

function() thisCanBeAlsoJavascript() {
    alert("this is safe");
}

Invalid input:

function() notFunny() {
    alert("I think it's not safe");
    console.log("And this");<% System.Web.HackEverything(); %>

    <%
    Console.WriteLine("This looks dangerous");
    %>
}
Some more text

How can I do this? I know I need to use lookarounds to reach the solution. I tried something like this ^(?<!<%)[\s\S]*(?!%>) for multiline text, but it matches entire invalid text. What should I change?

EDIT: To make it clear - I use C# DataAnnotations and RegularExpressionAttribute to validate my string. That's why I need regex that not match my input.


Solution

  • Try this

    ^(?!.*<%.*%>).*
    

    Allow all that does not include <% ... %>

    if c# == js than you need to replace all . with [\s\S]. otherwise just add m flag for multiline. m needed anyway to match ^ to beginning of string.

    See https://regex101.com/r/L1Q1lf/1