开发者

Regular expression to stop special characters except _ in between not in start

开发者 https://www.devze.com 2023-04-11 23:26 出处:网络
I am trying to create a regular exp toto stop user entering special character at any place int he string but alowing numbers and underscore inside string except at starting point .

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:

Regular expression to stop special characters except _ in between not in start

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号