I’m still kinda new to using Regular Expressions, so here’s my plight. I have some rules for acceptable usernames and I’m trying to make an expression for them.
Here they are:
- 1-15 Characters
- a-z, A-Z, 0-9, and spaces are acceptable
- Must begin with a-z or A-Z
- Cannot end in a space
- Cannot contain two spaces in a row
This is as far as I’ve gotten with it.
/^[a-zA-Z]{1}([a-zA-Z0-9]|\s(?!\s)){0,14}[^\s]$/
It works, for the most part, but doesn’t match a single character such as “a”.
Can anyone help me out here? I’m using PCRE in PHP if that makes any difference.
Try this:
The look-ahead assertion
(?=.{1,15}$)checks the length and the rest checks the structure:[a-zA-Z]ensures that the first character is an alphabetic character;[a-zA-Z0-9]*allows any number of following alphanumeric characters;(?: [a-zA-Z0-9]+)*allows any number of sequences of a single space (not\sthat allows any whitespace character) that must be followed by at least one alphanumeric character (see PCRE subpatterns for the syntax of(?:…)).You could also remove the look-ahead assertion and check the length with
strlen.