1

I'm trying to create a regex pattern that allows the user to create a username with the following specifications. (For the purposes of this initial pattern, I'm only using standard american English alphabet.

The first character must be an alphabetic letter (uppercase or lowercase). [a-zA-Z] The last character must be a alphanumeric (uppercase or lowercase). [a-zA-Z0-9] Any characters in between must be letters or numbers with one rule:

The user can use a period(.), dash(-), or underscore(_) but it must be followed by an alphanumeric character. So no repeats of one or more of these characters at a time.

I've tried the following regex pattern but am not getting the results I was hoping for. Thanks for taking the time to help me on this.

^[a-zA-Z]([a-zA-Z0-9]+[._-]?[a-zA-Z0-9]+)+$

EDIT

It might actually be working the way I expected. But I'm always getting two matches returned to me. The first one being the entire valid string, the second being a shortened version of the first string usually chopping off the first couple of characters.

Examples of valid inputs:

  • Spidy
  • Spidy.Man
  • Ama-za-zing_Spidy

Examples of invalid inputs:

  • Extreme___Spidy (repeated underscores)
  • The_-_Spidy (repeated special characters)
  • _ _ SPIDY _ _ (starts and ends with special characters)

2 Answers 2

5

Sounds like this pattern:

^[a-zA-Z]([._-]?[a-zA-Z0-9])*$
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this is a much nicer representation of my own. Any ideas on why my text.match(pattern) is returning multiple matches?
The round parentheses double as a capture group, so you're also seeing the captured value. You can discard all that, since all you need to know is whether the string matched or not.
1
^[a-zA-Z]([._-]?[a-zA-Z0-9]+)*$

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.