最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regular expression to validate a string starts with a char and contains allowed chars - Stack Overflow

programmeradmin4浏览0评论

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

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

The expression must validate the following

  • String first char MUST start with a-z (no alpha)
  • String can contain any char in range a-z (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

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

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

The expression must validate the following

  • String first char MUST start with a-z (no alpha)
  • String can contain any char in range a-z (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

Share Improve this question asked Jan 14, 2021 at 12:38 Hans PreutzHans Preutz 6992 gold badges11 silver badges29 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 4

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

https://regex101./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 a-z but then has 0-49 of a-z, 0-9 or .-

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

Edit: Not sure if you intended to allow upper and lowercase, but if you did both character classes could add A-Z 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
  • [a-z] Match a single char a-z
  • (?=[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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论