排除字符串开头和结尾的特殊字符

时间:2013-04-22 11:11:10

标签: c# asp.net regex

我想要一个正则表达式来排除字符串

的开头和结尾的特殊字符

我尝试了这段代码,但它无效

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>

1 个答案:

答案 0 :(得分: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_ -]*"