简体   繁体   中英

Regex Expression allowing special characters

I'm using an online regex checker such as regex101 to check my regex which is to be used by javascript such as ( working but cut down regex for example only)

state = /^[a-zA-Z0-9]$/.test($(control).val())

My Regex is

(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9].{5,19}

Which when cut down into chunks should hopefully mean...

(?=.*[A-Z])  - Must include an Upper case char
(?=.*[0-9])  - Must include a numeric 
[a-zA-Z0-9. ]  - Can include any lower  or upper case char, or Numeric, a period or space
.            - Matching previous
{5,19}       - the string must be 6-20 characters in length

This however still allows special characters such as !.

I've not used \\d for decimals as I believe [0-9] should be more strict in this regard, and removed the period and space to see whether this was the cause, to no avail.

Where have I gone wrong to be allowing special characters?

You need to remove the last . which you think is matching previous, it actually matches any character except for newline, so this is where the ! is getting through.

So (?=.*[AZ])(?=.*[0-9])[a-zA-Z0-9].{5,19} should be (?=.*[AZ])(?=.*[0-9])[a-zA-Z0-9]{5,19}

Also just thought i'd mention there is no difference between \\d and [0-9] whatsoever.

UPDATED - this following should fix the issues you were seeing with the regex - (?=.*[AZ])(?=.*[0-9])[a-zA-Z0-9\\.\\s]{6,20}$

  • Added \\. (to allow a .)
  • Added \\s (to allow whitespace characters)
  • Changed {5, 19} to {6, 20}$ to ensure the correct character match

If you want to test this version of the regex in regex101 here

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