0

I don't quite understand how to put a regex expression together. I keep trying to combine stuff from similar threads I've seen here, with stuff I've been googling, but I seem to be doing this all wrong.

The only thing I can get right is

[A-Za-z0-9]{6,20}

But when I try to add more to the pattern, it doesn't seem to be working.

NOTE This is using the HTML input pattern attribute. I would appreciate some assistance on this, but I would also appreciate if someone could break down the solution for me, so I could comprehend it a little better.

  • Username can contain uppercase/lowercase letters
  • Username can contain numbers
  • Username can contain underscore, hyphen or period
  • Username cannot contain spaces
  • Username cannot contain special characters
  • Username should be between 6-20 characters in length

I've tried something like this:

[A-Za-z0-9_-]{6,20}\S

I feel like I'm sort of there, but not quite there.

1
  • You could match a word character, dot or a hyphen without the \S at the end [\w.-]{6,20} Commented Oct 19, 2018 at 6:49

1 Answer 1

2

The following should work:

[A-Za-z0-9\-_\.]{6,20}

To break it down:

  • A-Z any uppercase char
  • a-z any lowercase char
  • 0-9 any number
  • \- hyphen (escaped by '\' depending on what order it is put)
  • . period

The hyphen doesn't need be escaped depending on the ordering:

[A-Za-z0-9-_.]{6,20}

or

[A-Za-z0-9_.-]{6,20}

should work, while the following shouldn't:

[A-Za-z0-9_-.]{6,20}

In the pattern you were using the \S matches any character that is not whitespace so it would expect an extra character after the 6-20 char string. As no white space (\s) is within the square brackets, the omission means spaces are not allowed; this is the same for special characters.

Sign up to request clarification or add additional context in comments.

1 Comment

Period doesn't need to be escaped in a character class. [A-Za-z0-9_] can be shortened in \w

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.