如何在正则表达式中允许双引号?

时间:2012-11-26 13:00:59

标签: asp.net regex

我有一个文本框:

<asp:RegularExpressionValidator ID="ValidateTitleCharacters" runat="server" 
    ValidationExpression="^[a-zA-Z0-9@+'.!#$',:;=/\(\),\-\s]{1,255}$"
    ControlToValidate="title" Text="You have entered a character(s) that is not allowed in the title."
    ErrorMessage="You have entered a character(s) that is not allowed in the title." />

我想也允许“字符。如何修改正则表达式字符串???

我试过了:

<asp:RegularExpressionValidator ID="ValidateTitleCharacters" runat="server" 
    ValidationExpression="^[a-zA-Z0-9@+'.!#$'\",:;=/(),\-\s]{1,255}$"
    ControlToValidate="title" Text="You have entered a character(s) that is not allowed in the title."
    ErrorMessage="You have entered a character(s) that is not allowed in the title." />

<asp:RegularExpressionValidator ID="ValidateTitleCharacters" runat="server" 
    Validat‌​ionExpression="^[a-zA-Z0-9@+'.!#$',:;=/()(""),\-\s]{1,255}$"
    ControlToValidate="title" Text="You have entered a character(s) that is not allowed in the title."
    ErrorMessage="You have entered a character(s) that is not allowed in the title." />

两次尝试都破坏了字符串。

1 个答案:

答案 0 :(得分:9)

从您发布的片段中,似乎正则表达式嵌入在标记中 - 这意味着您需要将双引号字符转义为HTML字符实体。

使用&quot;

ValidationExpression="^[a-zA-Z0-9@+'.!#$'&quot;,:;=/\(\),\-\s]{1,255}$"

ASP.NET引擎会将字符实体转换为"

或者,在代码中设置ValidationExpression值(例如,在OnInit中):

ValidateTitleCharacters.ValidationExpression = 
                                  "^[a-zA-Z0-9@+'.!#$'\",:;=/\(\),\-\s]{1,255}$";