Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to add underscore to my regex

Tags:

regex

I'm new to regular expression and just can't seem to figure this out:

'/^[A-Za-z0-9](?:.[A-Za-z0-9]+)$/'

As it's right now it allows dots anytime after the first char and I like to add _ so that it allows both. Thanks


2 Answers

Actually, /^[A-Za-z0-9](?:.[A-Za-z0-9]+)$/ allows any character after the first letter, since . is a special character matching anything.

Use

/^[A-Za-z0-9](?:[._][A-Za-z0-9]+)$/

Inside character classes (denoted by the sqaure brackets), the dot loses its special meaning.

like image 86
Jens Avatar answered Sep 22 '25 07:09

Jens


/^[A-Za-z0-9]*(?:[._][A-Za-z0-9]+)*$/

In your present state regex would allow any character (including dot).

like image 31
SilentGhost Avatar answered Sep 22 '25 06:09

SilentGhost