gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:47:37 26 4
gpt4 key购买 nike

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

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

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

关于c# - 排除字符串开头和结尾的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16145719/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com