Skip to main content
 首页 » 编程设计

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

2024年02月13日21Terrylee

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

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

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> 

请您参考如下方法:

您几乎就在那里,只需添加 anchor 以将匹配项绑定(bind)到字符串的开头或结尾,并告诉正则表达式引擎匹配多个字符:

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_ -]*"