简体   繁体   中英

Regular expression to validate a string starts with a char and contains allowed chars

I need help with my regular expression written in javascript. I have tried using the regularExpression generator online, and the best i can come up with is the this:

^[a-z.-]{0,50}$

The expression must validate the following

  • String first char MUST start with az (no alpha)
  • String can contain any char in range az (no alpha), 0-9 and the characters dash "-" and dot "."
  • String can be of max length 50 chars

Examples of success strings

  • username1
  • username.lastname
  • username-anotherstring1
  • this.is.also.ok

No good strings

  • 1badusername
  • .verbad
  • -bad
  • also very bad has spaces

// Thanks

Almost (assuming "no alpha" means no uppercase letters)

https://regex101.com/r/O9hvLP/3

^[a-z]{1}[a-z0-9\.-]{0,49}$

The {1} is optional, I put it there for descriptive reasons

I think this should cover what you want

^[a-z][a-z0-9.-]{0,49}$

That is starts az but then has 0-49 of az , 0-9 or .-

Live example: https://regexr.com/5k8eu

Edit: Not sure if you intended to allow upper and lowercase, but if you did both character classes could add AZ as well!

If the . and - can not be at the end, and there can not be consecutive ones, another option could be:

^[a-z](?=[a-z0-9.-]{0,49}$)[a-z0-9]*(?:[.-][a-z0-9]+)*$

Explanation

  • ^ Start of string
  • [az] Match a single char az
  • (?=[a-z0-9.-]{0,49}$) Assert 0-49 chars to the right to the end of string
  • [a-z0-9]* Match optional chars a-z0-9
  • (?:[.-][a-z0-9]+)* Optionally match either . or - and 1+ times a char a-z0-9
  • $ End of string

Regex demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM