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.
In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$".
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.
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.
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
^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With