Regular expression to stop special characters except _ in between not in start
I am trying to create a regular exp to to stop user entering special character at any place int he string but alowing numbers and underscore inside string except at starting point .
scenarios
abhi_3123123 valid
abhi___ASDFAS valid
3425_asdfasdf invalid
_asdfasdf invalid
sometext(having any spcl character at any place) invalid
only underscore should be allowed only in between not in start and end
updated code
i m calling this code on textchange event of my textbox
string regEx = @"^[a-zA-Z][a开发者_StackOverflow中文版-zA-Z0-9_]*(?<!_)$";
if (System.Text.RegularExpressions.Regex.IsMatch(txtFunctionName.Text, regEx))
{
//no error
}
else
{
// show error
}
this code is showing error
Assuming you only want to allow ASCII letters, digits and underscore, use
^[a-zA-Z]\w*(?<!_)$
in Java or
^[a-zA-Z][a-zA-Z0-9_]*(?<!_)$
in .NET.
Explanation:
^ # 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
See it in action:
精彩评论