Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

regex

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-zA-Z0-9_]*(?<!_)$";
 if (System.Text.RegularExpressions.Regex.IsMatch(txtFunctionName.Text, regEx))
 {
   //no error
 }
 else
 {
   // show error
 }

this code is showing error

like image 395
Abhi Avatar asked Nov 14 '22 16:11

Abhi


1 Answers

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: Screenshot from RegexBuddy

like image 111
Tim Pietzcker Avatar answered Mar 15 '23 23:03

Tim Pietzcker