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

javascript - RegEx: Must have at least one number and letter but no other characterswhitespace - Stack Overflow

programmeradmin1浏览0评论

Got a bit stuck (RegEx isn't my strong point at all!) - I need an expression that will validate against any string containing only numbers and letters but must have at least one of each (upper and lowercase are interchangeable and allowed). It cannot contain special characters or whitespace.

Doing some prior research I have found this but it doesn't exclude whitespace and despite my attempts to do so I cannot modify it to exclude whitespace and special characters:

^.*(?=.*\d)(?=.*[a-zA-Z]).*$

Some examples of strings that need to validate:

  • ieoEon43
  • 43ifsiojfdfs
  • 6i
  • ijf943kNFSfsf

Any help would be much appreciated! If it matters I am running these expressions in JavaScript.

Got a bit stuck (RegEx isn't my strong point at all!) - I need an expression that will validate against any string containing only numbers and letters but must have at least one of each (upper and lowercase are interchangeable and allowed). It cannot contain special characters or whitespace.

Doing some prior research I have found this but it doesn't exclude whitespace and despite my attempts to do so I cannot modify it to exclude whitespace and special characters:

^.*(?=.*\d)(?=.*[a-zA-Z]).*$

Some examples of strings that need to validate:

  • ieoEon43
  • 43ifsiojfdfs
  • 6i
  • ijf943kNFSfsf

Any help would be much appreciated! If it matters I am running these expressions in JavaScript.

Share Improve this question asked Jul 7, 2014 at 15:07 trvotrvo 6851 gold badge11 silver badges24 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

Try this:

/^(?=.*[a-z])(?=.*\d)[a-z\d]+$/i

Regex101 Demo

Explanation:

Debuggex Demo

Edit: Fixed special characters issue.

Another attempt for fun and glory! (it's shorter!)

^([a-z]+\d+|\d+[a-z]+)\w*$

Debuggex Demo

EDIT3:

Made a small fix and it's now DOUBLE the speed of the other answer!!!

JSPERF

Iv done a demo on regxr 1.0 based on what I understood from your question.

If you follow this link you can see the demo yourself: Regexr demo

UPDATED: The regex is : /^([a-z]+[0-9]+|[0-9]+[a-z]+)$/

You can make it case in sensitive: /^([a-z]+[0-9]+|[0-9]+[a-z]+)$/i

发布评论

评论列表(0)

  1. 暂无评论