不匹配任何html标记的Regex

时间:2021-06-29 19:35:25

I am really bad with regexps, what I want is a regexp that does not match any html tags (for user input validation).

我非常不喜欢regexp,我想要的是不匹配任何html标记的regexp(用于用户输入验证)。

What I want is negative of this:

我想要的是负的

<[^>]+>

What I currently have is

我现在拥有的是

public class MessageViewModel
{
    [Required]
    [RegularExpression(@"<[^>]+>", ErrorMessage = "No html tags allowed")]
    public string UserName { get; set; }
}

but it does opposite of what I want - allows usernames only with html tags

但是它做的与我想要的相反——只允许使用html标签的用户名

1 个解决方案

#1


3  

Regular expressions cannot do "negative" matches.

正则表达式不能做“否定”匹配。

But they can do "positive" matches and you can then throw out of the string everything that they have found.

但是它们可以做"正"匹配然后你可以把它们找到的所有东西都扔出弦。


Edit - after the question was updated, things became a little clearer. Try this:

在问题被更新后,事情变得更清晰了。试试这个:

public class MessageViewModel
{
    [Required]
    [RegularExpression(@"^(?!.*<[^>]+>).*", ErrorMessage = "No html tags allowed")]
    public string UserName { get; set; }
}

Explanation:

解释:

^            # start of string
(?!          # negative look-ahead (a position not followed by...)
  .*         #   anything
  <[^>]+>    #   something that looks like an HTML tag
)            # end look-ahead
.*           # match the remainder of the string

#1


3  

Regular expressions cannot do "negative" matches.

正则表达式不能做“否定”匹配。

But they can do "positive" matches and you can then throw out of the string everything that they have found.

但是它们可以做"正"匹配然后你可以把它们找到的所有东西都扔出弦。


Edit - after the question was updated, things became a little clearer. Try this:

在问题被更新后,事情变得更清晰了。试试这个:

public class MessageViewModel
{
    [Required]
    [RegularExpression(@"^(?!.*<[^>]+>).*", ErrorMessage = "No html tags allowed")]
    public string UserName { get; set; }
}

Explanation:

解释:

^            # start of string
(?!          # negative look-ahead (a position not followed by...)
  .*         #   anything
  <[^>]+>    #   something that looks like an HTML tag
)            # end look-ahead
.*           # match the remainder of the string