简体   繁体   中英

Regex for allow some special characters but not allowing spaces in javascript?

I am wrote the following regex for accepting one lowercase and one uppercase letter , one digit and one special character(!@#$%).

/^(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%]).*$/

But the above regex accepts space also . How to restrict space using regex in javascript.

The easiest way here would be to just match [^ ]* instead of .* in your pattern:

/^(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%])[^ ]*$/
                                                      ^^^ change here

If by "space" you actually mean any whitespace character, then use \\S instead:

/^(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%])\S*$/

Edit:

If you instead want to restrict to only alphanumeric (uppercase or lowercase) along with a fixed set of symbols, then use this pattern:

/^(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%])[A-Za-z0-9!@#$%]*$/

尝试这个:

^(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%])[^ ]*$

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