简体   繁体   English

RegularExpression DataAnnotation验证HTML标签

[英]RegularExpression DataAnnotation to validate Html tags

This regular expression validates html tags that include attributes could someone correct this code to work in C# RegularExpression. 此正则表达式验证包含属性的html标签,有人可以纠正此代码以在C#RegularExpression中工作。 The problem with this expression is the quotes it stops at the first quote because it's part of the expression doesn't any one know how to fix this or does anyone have an alternative. 这个表达式的问题是引号在第一个引号处停止,因为它是表达式的一部分,没有人知道如何解决这个问题,或者没有人有其他选择。 PS does anyone know of a C# .net regular expression site to test their expressions PS没有人知道C#.net正则表达式站点来测试其表达式

Here is the code: 这是代码:

[RegularExpression(@"</?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)/?>")]

this is the validation output after adding double quotes to th expression 这是在表达式中添加双引号后的验证输出

 data-val-regex-pattern="&lt;/?\w+((\s+\w+(\s*=\s*(?:&quot;.*?&quot;|&#39;.*?&#39;|[^&#39;&quot;>\s]+))?)+\s*|\s*)/?>"

It sounds like your issue is that the string literal doesn't compile as valid C#. 听起来您的问题是字符串文字不能编译为有效的C#。 When using verbatim string literals (string literals that begin with @ ) you can escape " characters by simply doubling them, "" . Your code should look like: 使用逐字字符串文字(以@开头的字符串文字)时,您可以通过将字符""简单地加倍来转义"字符。您的代码应如下所示:

[RegularExpression(@"</?\w+((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>")]

Further Reading 进一步阅读

However, I'd recommend tweaking the pattern slightly, like this: 但是,我建议稍微调整一下模式,如下所示:

[RegularExpression(@"</?\w+((\s+\w+(\s*=\s*(?:""[^""]*""|'[^']*'|[^'"">\s]+))?)+\s*|\s*)/?>")]

Which actually represents the pattern: 实际上代表了模式:

</?\w+((\s+\w+(\s*=\s*(?:"[^"]*"|'[^']*'|[^'">\s]+))?)+\s*|\s*)/?>

If this pattern were later converted to html it would look something like this: 如果此模式以后被转换为html,它将类似于以下内容:

&lt;/?\w+((\s+\w+(\s*=\s*(?:&quot;[^&quot;]*&quot;|&#39;[^&#39;]*&#39;|[^&#39;&quot;>\s]+))?)+\s*|\s*)/?>
  • &lt; represents an encoded < character 代表一个已编码的<字符
  • &quot; represents an encoded " character 表示一个编码"字符
  • &#39; represents an encoded ' character 代表一个编码'字符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM