A regular expression to stop special characters except _ between them at the beginning

I am trying to create a regular exp to stop the user entering a special character anywhere in the int string, but instead of the number and underscore inside the string except the starting point.

scripts

        abhi_3123123  valid
        abhi___ASDFAS valid
        3425_asdfasdf invalid
        _asdfasdf     invalid
        sometext(having any spcl character at any place) invalid

only underlining should be allowed only between them not at the beginning and at the end

updated code

im calling this code in a text event of my text field

 string regEx = @"^[a-zA-Z][a-zA-Z0-9_]*(?<!_)$";
 if (System.Text.RegularExpressions.Regex.IsMatch(txtFunctionName.Text, regEx))
 {
   //no error
 }
 else
 {
   // show error
 }

this code shows an error

+5
source share
1 answer

Assuming you want to allow letters, numbers, and ASCII 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 in action: Screenshot from RegexBuddy

+1
source

All Articles