Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression - starting and ending with a letter, accepting only letters, numbers and _

Tags:

regex

I'm trying to write a regular expression which specifies that text should start with a letter, every character should be a letter, number or underscore, there should not be 2 underscores in a row and it should end with a letter or number. At the moment, the only thing I have is ^[a-zA-Z]\w[a-zA-Z1-9_] but this doesn't seem to work properly since it only ever matches 3 characters, and allows repeated underscores. I also don't know how to specify requirements for the last character.

like image 251
jreid9001 Avatar asked May 12 '10 17:05

jreid9001


People also ask

How do I allow only letters and numbers in regex?

In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$".

How do I specify start and end in regex?

To match the start or the end of a line, we use the following anchors: Caret (^) matches the position before the first character in the string. Dollar ($) matches the position right after the last character in the string.

What character is at the beginning and end of a regular expression?

The caret ^ and dollar $ characters have special meaning in a regexp. They are called “anchors”. The caret ^ matches at the beginning of the text, and the dollar $ – at the end.


2 Answers

I'll take a stab at it:

/^[a-z](?:_?[a-z0-9]+)*$/i

Explained:

/
 ^           # match beginning of string
 [a-z]       # match a letter for the first char
 (?:         # start non-capture group
   _?          # match 0 or 1 '_'
   [a-z0-9]+   # match a letter or number, 1 or more times
 )*          # end non-capture group, match whole group 0 or more times
 $           # match end of string
/i           # case insensitive flag

The non-capture group takes care of a) not allowing two _'s (it forces at least one letter or number per group) and b) only allowing the last char to be a letter or number.

Some test strings:

"a": match
"_": fail
"zz": match
"a0": match
"A_": fail
"a0_b": match
"a__b": fail
"a_1_c": match
like image 116
gnarf Avatar answered Nov 13 '22 07:11

gnarf


^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$
like image 23
Alan Moore Avatar answered Nov 13 '22 05:11

Alan Moore