我正在尝试创建一个常规 exp 以阻止用户在字符串中的任何位置输入特殊字符,但除了起始点之外,在字符串中允许数字和下划线。
场景
abhi_3123123 valid
abhi___ASDFAS valid
3425_asdfasdf invalid
_asdfasdf invalid
sometext(having any spcl character at any place) invalid
只能在开始和结束之间使用下划线
更新代码
我在我的文本框的 textchange 事件上调用这段代码
string regEx = @"^[a-zA-Z][a-zA-Z0-9_]*(?<!_)$";
if (System.Text.RegularExpressions.Regex.IsMatch(txtFunctionName.Text, regEx))
{
//no error
}
else
{
// show error
}
这段代码显示错误
最佳答案
假设您只想允许 ASCII 字母、数字和下划线,请使用
^[a-zA-Z]\w*(?<!_)$
Java 或
^[a-zA-Z][a-zA-Z0-9_]*(?<!_)$
在 .NET 中。
解释:
^ # Start of string
[a-zA-Z] # First character: ASCII letter
[a-zA-Z0-9_]* # Following characters: ASCII letter, digit or underscore
(?<!_) # Assert that last character isn't an underscore
$ # End of string
查看实际效果:
关于c# - 正则表达式停止除 _ 之外的特殊字符 not in start,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7724174/