我想要一个正则表达式来排除字符串
的开头和结尾的特殊字符我尝试了这段代码,但它无效
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>
答案 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_ -]*"