Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match 2-20 alphanumeric characters, allowing a single hyphen anywhere in the string

Tags:

regex

php

I'm trying to learn how to use preg_match. I want users to be only allowed to sign up with username between 2-20 characters which can contain a-zA-Z0-9.

Now the tricky part where Im getting lost, I want them to be able to include one hyphen anywhere in the username so,

-Brad = TRUE

--Brad = FALSE

B-Rad = TRUE
like image 209
Bradley Roberts Avatar asked Mar 11 '12 16:03

Bradley Roberts


2 Answers

You can build this up step-by-step. You want a username that consist of 2-20 specific characters:

^[a-zA-Z0-9]{2,20}$

Now you want to allow a single - character somewhere in there (the trick part):

The - character is only allowed if it is not followed up by another - to the end of the string:

[-](?=[^-]*$)

This is a so called Lookahead assertion. Combined with an alternation, the regex completes to:

^(?:[a-zA-Z0-9]|[-](?=[^-]*$)){2,20}$

Compared to the other answers given, this one respects your length specification.

like image 98
hakre Avatar answered Oct 12 '22 13:10

hakre


You could use preg_match with:

\w*-?\w*

It will ensure that one hyphen exists, but will also match just a hyphen. You can also use:

(\w*-?\w+)|(\w+-?\w*)

To avoid matching only a hyphen. Or you can check if the match has length > 1.

You said to be able to, so I assumed the hyphen isn't a requirement. If it is, remove the ? in the regex.

If you plan on matching in a sentence, you could use a word break (\b) with the \w+ part. If you're using this on a trimmed string then add ^ and $ to the start and end respectively to avoid matching --Bra-d as true.

like image 26
Aram Kocharyan Avatar answered Oct 12 '22 15:10

Aram Kocharyan