1

我想要一个正则表达式来排除字符串开头和结尾的特殊字符

我试过这段代码,但它不工作

String strFileName = Regex.Replace(FileName, @"[^A-Za-z0-9-_ ]", "");

<asp:RegularExpressionValidator ID = "Regular" 
            ValidationGroup = "valGroup" runat="server" ControlToValidate = "txtreport"
            ErrorMessage = "Please enter valid data."
            ValidationExpression = "([a-z]|[A-Z]|[0-9])*">
</asp:RegularExpressionValidator>
4

1 回答 1

4

您快到了,只需添加锚点以将匹配项绑定到字符串的开头或结尾,并告诉正则表达式引擎匹配多个字符:

String strFileName = Regex.Replace(FileName, 
    @"^              # Match the start of the string
    [^A-Z0-9_ -]+    # followed by one or more characters except these
    |                # or
    [^A-Z0-9_ -]+    # Match one or more characters except these
    $                # followed by the end of the string", 
    "", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

另外,你的ValidationExpression很奇怪。

ValidationExpression="[a-zA-Z0-9]*"

意思相同,但不允许_,<space>并且-您的“特殊字符替换器”正在忽略。所以你可能想使用

ValidationExpression="[a-zA-Z0-9_ -]*"
于 2013-04-22T11:22:38.207 回答