Regex for checking usernames with at least one letter and without special characters

I am trying to write a username check that has the following limitations:

  • Must contain at least 1 letter (a-zA-Z)
  • May contain nothing more than numbers, letters or underscores

The following examples are available: abc123, my_name, 12345a

The following invalid examples are: 123456, my_name !, _1235

I found something about using positive images for the letter constraint: (? =. * [A-zA-Z]), and it looks like there might be some kind of negative outlook on the second constraint, but I'm not sure how to mix them into one regular expression. (Please note ... I don’t quite understand what it is doing. * The part inside lookahead ...)

This is something like this: / (? =. * [A-zA-Z]) (?!. * [^ A-zA-Z0-9 _]) /

Edit:

Since the question is asked by a regular expression, the answer I accept is this:

 /^[a-zA-Z0-9_]*[a-zA-Z][a-zA-Z0-9_]*$/

However, what I'm actually going to implement is Brian Oakley’s proposal to break it down into several smaller checks. This makes it easier to read and expand in the event that requirements change. Thanks everyone!

And since I tagged this with ruby-on-rails, I will include the code that I use:

validate :username_format    

def username_format
  has_one_letter = username =~ /[a-zA-Z]/
  all_valid_characters = username =~ /^[a-zA-Z0-9_]+$/
  errors.add(:username, "must have at least one letter and contain only letters, digits, or underscores") unless (has_one_letter and all_valid_characters)
end
+5
source share
3 answers

/^[a-zA-Z0-9_]*[a-zA-Z][a-zA-Z0-9_]*$/: 0 or more valid characters, followed by a single alphabetical index, followed by 0 or more valid characters, which are limited to both the beginning and the end of the line.

+6
source

, - , , . .

- . , - :

if no_illegal_characters(string) && contains_one_alpha(string) {
    ...
}

^[a-zA-Z0-9_]+$, [a-zA-Z].

, , . , , .

+6

The simplest regex that solves your problem:

/^[a-zA-Z0-9][a-zA-Z0-9_]*$/

I recommend you try it live on http://rubular.com/

+2
source

All Articles